Reputation: 559
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?
Upvotes: 1
Views: 2272
Reputation: 273
You can use str.capitalize
word = "dalmatian dalmatin"
word.capitalize()
Dalmatin dalmatin
or str.title
word = "dalmatian dalmatin"
word.title()
Dalmatin Dalmatin
Upvotes: 4
Reputation: 2233
You can use the string method capitalize
to do what you're looking for.
word = 'bla'
print word.capitalize()
Bla
Upvotes: 1
Reputation: 20560
You can't; Python strings are immutable. You have to create a new string:
word = word[0].upper() + word[1:]
Upvotes: 6