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()
Related
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.
Given a string, I have to reverse every word, but keeping them in their places.
I tried:
def backward_string_by_word(text):
for word in text.split():
text = text.replace(word, word[::-1])
return text
But if I have the string Ciao oaiC, when it try to reverse the second word, it's identical to the first after beeing already reversed, so it replaces it again. How can I avoid this?
You can use join in one line plus generator expression:
text = "test abc 123"
text_reversed_words = " ".join(word[::-1] for word in text.split())
s.replace(x, y) is not the correct method to use here:
It does two things:
find x in s
replace it with y
But you do not really find anything here, since you already have the word you want to replace. The problem with that is that it starts searching for x from the beginning at the string each time, not at the position you are currently at, so it finds the word you have already replaced, not the one you want to replace next.
The simplest solution is to collect the reversed words in a list, and then build a new string out of this list by concatenating all reversed words. You can concatenate a list of strings and separate them with spaces by using ' '.join().
def backward_string_by_word(text):
reversed_words = []
for word in text.split():
reversed_words.append(word[::-1])
return ' '.join(reversed_words)
If you have understood this, you can also write it more concisely by skipping the intermediate list with a generator expression:
def backward_string_by_word(text):
return ' '.join(word[::-1] for word in text.split())
Splitting a string converts it to a list. You can just reassign each value of that list to the reverse of that item. See below:
text = "The cat tac in the hat"
def backwards(text):
split_word = text.split()
for i in range(len(split_word)):
split_word[i] = split_word[i][::-1]
return ' '.join(split_word)
print(backwards(text))
I just started to learn python a few months ago so I'm a newbie here. I was trying to capitalize the first letter of every word in a string. When the input is "hello world" (for example) it works perfectly, but with some inputs like "i love coding" it returns this "I Love CodIng" and it just doesn't make sense to me. Could someone explain to me why this is happening? Here's the code:
def LetterCapitalize(str):
str = str.replace(str[0], str[0].upper())
for i in range(len(str)):
try:
if str[i] == ' ':
str = str.replace(str[i+1], str[i+1].upper())
else:
continue
except IndexError:
break
return str
The str.replace method replaces all occurrences of the given substring in the given main string, so by replacing the letter i with I in i love coding it replaces both is in the string.
Since strings are immutable you can instead convert the given string to a list of characters, so that you can iterate through the list, replace the character if it's either at the start of the string or preceded by a space, and join the list back to a string in the end:
def LetterCapitalize(s):
l = list(s)
for i, c in enumerate(l):
if not i or l[i - 1] == ' ':
l[i] = c.upper()
return ''.join(l)
so that LetterCapitalize('i love coding') returns:
I Love Coding
The problem with the code is your first line,
str = str.replace(str[0], str[0].upper())
Here you replace first letter with its capital, but also you replace that letter in all the following string.
Example :
LetterCapitalize("hello hoher") -> 'Hello HoHer'
You need to modify single character at a given position in the string and not replace all the occurring letters. You should try to work with string as a list. Here is a helpful link : Change one character in a string?
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)
def remove_char(text):
for letter in text[1]:
text[0] = text[0].replace(letter," ")
return text[0]
This is returning:
'str' object does not support item assignment
Why? And how can I make this work?
In Python, strings are not mutable, which means they cannot be changed. You can, however, replace the whole variable with the new version of the string.
Example:
text = ' ' + text[1:] # replaces first character with space
Strings are immutable. By trying:
text[0] = text[0].replace(letter," ")
you are trying to access the string and change it, which is disallowed due to the string's immutability. Instead, you can use a for loop and some slicing:
for i in range(0, len(y)):
if y[i] == ",":
print y[i+1:len(y)]
break
You can change the string a variable is assigned to (second piece of code) rather than the string itself (your piece of code).
Assuming that the parameter text is a string, the line for letter in text[1]: doesn't make much sense to me since text[1] is a single character. What's the point of iterating over a one-letter string?
However, if text is a list of strings, then your function doesn't throw any exceptions, it simply returns the string that results from replacing in the first string (text[0]) all the letters of the second string (text[1]) by a blank space (" ").
The following examples show how remove_char works when its argument is a list of strings:
In [462]: remove_char(['spam', 'parrot', 'eggs'])
Out[462]: 's m'
In [463]: remove_char(['bar', 'baz', 'foo'])
Out[463]: ' r'
In [464]: remove_char(['CASE', 'sensitive'])
Out[464]: 'CASE'
Perhaps this is not the intended behaviour...