Bodhidarma
Bodhidarma

Reputation: 559

How to change letters in a string in python

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

Answers (4)

juree
juree

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

doru
doru

Reputation: 9110

>>> "dalmatian".title()
'Dalmatian'
>>> 

Upvotes: 2

Amaury Medeiros
Amaury Medeiros

Reputation: 2233

You can use the string method capitalize to do what you're looking for.

word = 'bla'
print word.capitalize()
Bla

Upvotes: 1

Benjamin Peterson
Benjamin Peterson

Reputation: 20560

You can't; Python strings are immutable. You have to create a new string:

word = word[0].upper() + word[1:]

Upvotes: 6

Related Questions