I am trying to change the first character in a string to be uppercase. I approached it like this:
word = "dalmatian"
word[0] = word[0].upper()
print word
However I produce this error
Traceback (most recent call last):
File "/Users/Tom/Documents/coolone.py", line 3, in <module>
word[0] = word[0].upper()
TypeError: 'str' object does not support item assignment
Is there a way around this?
You can't; Python strings are immutable. You have to create a new string:
word = word[0].upper() + word[1:]
You can use str.capitalize
word = "dalmatian dalmatin"
word.capitalize()
Dalmatin dalmatin
or str.title
word = "dalmatian dalmatin"
word.title()
Dalmatin Dalmatin
>>> "dalmatian".title()
'Dalmatian'
>>>
You can use the string method capitalize
to do what you're looking for.
word = 'bla'
print word.capitalize()
Bla
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.