change the first word of string to the first letter - python

I want to change the first word of a string to the first letter of that word. For organisms, you can write "Arabidopsis thaliana" or "A. thaliana".
Because the String names are sometimes too long for my purpose I want to change this, so the string becomes shorter.
I tried to find a similar question, but it is always removing the first word or make the first letter uppercase or replacing the first word with a specific character, but never with the first character of the word itself.

Use replace() :
>>> s = 'Arabidopsis thaliana'
>>> s.replace(s.split()[0], s[0])
'A thaliana'
In the rare case, according to mrCarnivore if the first word is occurring multiple times we could use maxreplace parameter
>>> s = 'Arabidopsis Arabidopsis thaliana'
>>> s.replace(s.split()[0], s[0], 1)
'A Arabidopsis bologna'

This works:
s = 'Arabidopsis thaliana bologna'
l = s.split()
s2 = l[0][0] + '. ' + ' '.join(l[1:])
print(s2)

Related

Swap last two characters in a string, make it lowercase, and add a space

I'm trying to take the last two letters of a string, swap them, make them lowercase, and leave a space in the middle. For some reason the output gives me white space before the word.
For example if input was APPLE then the out put should be e l
It would be nice to also be nice to ignore non string characters so if the word was App3e then the output would be e p
def last_Letters(word):
last_two = word[-2:]
swap = last_two[-1:] + last_two[:1]
for i in swap:
if i.isupper():
swap = swap.lower()
return swap[0]+ " " +swap[1]
word = input(" ")
print(last_Letters(word))
You can try with the following function:
import re
def last_Letters(word):
letters = re.sub(r'\d', '', word)
if len(letters) > 1:
return letters[-1].lower() + ' ' + letters[-2].lower()
return None
It follows these steps:
removes all the digits
if there are at least two characters:
lowers every character
builds the required string by concatenation of the nth letter, a space and the nth-1 letter
and returns the string
returns "None"
Since I said there was a simpler way, here's what I would write:
text = input()
result = ' '.join(reversed([ch.lower() for ch in text if ch.isalpha()][-2:]))
print(result)
How this works:
[ch.lower() for ch in text] creates a list of lowercase characters from some iterable text
adding if ch.isalpha() filters out anything that isn't an alphabetical character
adding [-2:] selects the last two from the preceding sequence
and reversed() takes the sequence and returns an iterable with the elements in reverse
' '.join(some_iterable) will join the characters in the iterable together with spaces in between.
So, result is set to be the last two characters of all of the alphabetical characters in text, in reverse order, separated by a space.
Part of what makes Python so powerful and popular, is that once you learn to read the syntax, the code very naturally tells you exactly what it is doing. If you read out the statement, it is self-describing.

Pythonically remove the first X words of a string

How do I do it Pythonically?
I know how to delete the first word, but now I need to remove three.
Note that words can be delimited by amount of whitecap, not just a single space (although I could enforce a single white space if it must be so).
[Update] I mean any X words; I don't know hat they are.
I am considering looping and repeatedly removing the first word, joining together again, rinsing and repeating.
s = "this is my long sentence"
print ' '.join(s.split(' ')[3:])
This will print
"long sentence"
Which I think is what you need (it will handle the white spaces the way you wanted).
Try:
import re
print re.sub("(\w+)", "", "a sentence is cool", 3)
Prints cool
This can be done by simple way as:
In [7]: str = 'Hello, this is long string'
In [8]: str = str[3:]
In [9]: str
Out[9]: 'lo, this is long string'
In [10]:
Now you can update 3 on line In[8] with your X
You can use the split function to do this. Essentially, it splits the string up into individual (space separated, by default) words. These words are stored in a list and then from that list, you can access the words you want, just like you would with a normal list of other data types. Using the desired words you can then join the list to form a string.
for example:
import string
str='This is a bunch of words'
string_list=string.split(
#The string is now stored in a list that looks like:
#['this', 'is', 'a', 'bunch', 'of', 'words']
new_string_list=string_list[3:]
#the list is now: ['bunch', 'of', 'words']
new_string=string.join(new_string_list)
#you now have the string 'bunch of words'
You can also do this in fewer lines, if desired (not sure if this is pythonic though)
import string as st
str='this is a bunch of words'
new_string=st.join(st.split(str[3:])
print new_string
#output would be 'bunch of words'
You can use split:
>>> x = 3 # number of words to remove from beginning
>>> s = 'word1 word2 word3 word4'
>>> s = " ".join(s.split()) # remove multiple spacing
>>> s = s.split(" ", x)[x] # split and keep elements after index x
>>> s
'word4'
This will handle multiple spaces as well.

Capitalize first character of a word in a string

How is one of the following versions different from the other?
The following code returns the first letter of a word from string capitalize:
s = ' '.join(i[0].upper() + i[1:] for i in s.split())
The following code prints only the last word with every character separated by space:
for i in s.split():
s=' '.join(i[0].upper()+i[1:]
print s
For completeness and for people who find this question via a search engine, the proper way to capitalize the first letter of every word in a string is to use the title method.
>>> capitalize_me = 'hello stackoverlow, how are you?'
>>> capitalize_me.title()
'Hello Stackoverlow, How Are You?'
for i in s.split():`
At this point i is a word.
s = ' '.join(i[0].upper() + i[1:])
Here, i[0] is the first character of the string, and i[1:] is the rest of the string. This, therefore, is a shortcut for s = ' '.join(capitalized_s). The str.join() method takes as its argument a single iterable. In this case, the iterable is a string, but that makes no difference. For something such as ' '.join("this"), str.join() iterates through each element of the iterable (each character of the string) and puts a space between each one. Result: t h i s There is, however, an easier way to do what you want: s = s.title()

Python: Remove First Character of each Word in String

I am trying to figure out how to remove the first character of a words in a string.
My program reads in a string.
Suppose the input is :
this is demo
My intention is to remove the first character of each word of the string, that is
tid, leaving his s emo.
I have tried
Using a for loop and traversing the string
Checking for space in the string using isspace() function.
Storing the index of the letter which is encountered after the
space, i = char + 1, where char is the index of space.
Then, trying to remove the empty space using str_replaced = str[i:].
But it removed the entire string except the last one.
List comprehensions is your friend. This is the most basic version, in just one line
str = "this is demo";
print " ".join([x[1:] for x in str.split(" ")]);
output:
his s emo
In case the input string can have not only spaces, but also newlines or tabs, I'd use regex.
In [1]: inp = '''Suppose we have a
...: multiline input...'''
In [2]: import re
In [3]: print re.sub(r'(?<=\b)\w', '', inp)
uppose e ave
ultiline nput...
You can simply using python comprehension
str = 'this is demo'
mstr = ' '.join([s[1:] for s in str.split(' ')])
then mstr variable will contains these values 'his s emo'
This method is a bit long, but easy to understand. The flag variable stores if the character is a space. If it is, the next letter must be removed
s = "alpha beta charlie"
t = ""
flag = 0
for x in range(1,len(s)):
if(flag==0):
t+=s[x]
else:
flag = 0
if(s[x]==" "):
flag = 1
print(t)
output
lpha eta harlie

Replacing reoccuring characters in strings in Python 3.1

Is it possible to replace a single character inside a string that occurs many times?
Input:
Sentence=("This is an Example. Thxs code is not what I'm having problems with.") #Example input
^
Sentence=("This is an Example. This code is not what I'm having problems with.") #Desired output
Replace the 'x' in "Thxs" with an i, without replacing the x in "Example".
You can do it by including some context:
s = s.replace("Thxs", "This")
Alternatively you can keep a list of words that you don't wish to replace:
whitelist = ['example', 'explanation']
def replace_except_whitelist(m):
s = m.group()
if s in whitelist: return s
else: return s.replace('x', 'i')
s = 'Thxs example'
result = re.sub("\w+", replace_except_whitelist, s)
print(result)
Output:
This example
Sure, but you essentially have to build up a new string out of the parts you want:
>>> s = "This is an Example. Thxs code is not what I'm having problems with."
>>> s[22]
'x'
>>> s[:22] + "i" + s[23:]
"This is an Example. This code is not what I'm having problems with."
For information about the notation used here, see good primer for python slice notation.
If you know whether you want to replace the first occurrence of x, or the second, or the third, or the last, you can combine str.find (or str.rfind if you wish to start from the end of the string) with slicing and str.replace, feeding the character you wish to replace to the first method, as many times as it is needed to get a position just before the character you want to replace (for the specific sentence you suggest, just one), then slice the string in two and replace only one occurrence in the second slice.
An example is worth a thousands words, or so they say. In the following, I assume you want to substitute the (n+1)th occurrence of the character.
>>> s = "This is an Example. Thxs code is not what I'm having problems with."
>>> n = 1
>>> pos = 0
>>> for i in range(n):
>>> pos = s.find('x', pos) + 1
...
>>> s[:pos] + s[pos:].replace('x', 'i', 1)
"This is an Example. This code is not what I'm having problems with."
Note that you need to add an offset to pos, otherwise you will replace the occurrence of x you have just found.

Categories

Resources