[Tutor] How to change the char in string for Python
steve at pearwood.info
Sun Feb 24 13:32:54 CET 2013
On 24/02/13 21:56, Sudo Nohup wrote:
> Dear all,
> I want to change the value of a char in a string for Python. However, It
> seems that "=" does not work.
Strings are immutable, which means that you cannot modify them in place. You can only create a new string with the characters you want.
If you want to change one letter, the simplest way is with string slicing:
s = "Hello world!"
t = s[:6] + "W" + s[7:]
=> prints "Hello World!"
If you want to change many letters, the best way is to create a new list of the characters, and then join them:
s = "Hello"
chars = [chr(ord(c) + 13) for c in s]
t = ''.join(chars)
=> prints 'Uryy|'
Best still is to use the string methods, if you can, such as str.upper(), str.replace(), etc.
More information about the Tutor