[Tutor] How to change the char in string for Python

Asokan Pichai pasokan at talentsprint.com
Sun Feb 24 12:47:15 CET 2013


On Feb 24, 2013 4:27 PM, "Sudo Nohup" <sudo.nohup at gmail.com> wrote:
>
> Dear all,
>
> I want to change the value of a char in a string for Python. However, It
seems that "=" does not work.
>
> Could you help me? Thanks!
>
> str = "abcd"
> result = [char = 'a' for char in str if char == 'c']
>
>
> OR:
>
> str = 'abcd'
> for char in str:
>     if char == 'a':
>        char = 'c'
>
>
> OR:
>
> str = 'abcd'
> for i in range(len(str)):
>     if str[i] == 'a':
>        str[i] = 'c'
>
> (
> Traceback (most recent call last):
>   File "<stdin>", line 3, in <module>
> TypeError: 'str' object does not support item assignment
> )

Look up string replace function.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130224/a1950d03/attachment.html>


More information about the Tutor mailing list