Iteration over strings

Hexamorph hexamorph at
Tue Jul 31 20:32:38 CEST 2007

Jay Loden schrieb:
> Robert Dailey wrote:
>> str = "C:/somepath/folder/file.txt"
>> for char in str:
>>     if char == "\\":
>>         char = "/"

> strings in Python are immutable - in other words, they cannot be updated in place as you're doing above. However, that doesn't mean you can't achieve what you're after. In Python, the way to approach this problem since you cannot modify the string in place, is to create a new string object with the desired content:

Also note, that you are just extracting one char from the string 
into another variable (which you then change) and you are *not* 
getting any "reference" to the char in the string.

As has been alreagy told, use the str.replace() function

More information about the Python-list mailing list