Iteration over strings

Jay Loden python at jayloden.com
Tue Jul 31 14:07:05 EDT 2007


Robert Dailey wrote:
> Hi,
> 
> I have the following code:
> 
> str = "C:/somepath/folder/file.txt"
> 
> for char in str:
>     if char == "\\":
>         char = "/"
> 
> The above doesn't modify the variable 'str' directly. I'm still pretty new
> to Python so if someone could explain to me why this isn't working and what
> I can do to achieve the same effect I would greatly appreciate it.

Hi Robert, 

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:

    str = "C:/somepath/folder/file.txt"
    newstr = ""

    for char in str:
        if char == "\\":
            char = "/"
        newstr = newstr + char

    str = newstr


Note that for this particular example, there are also better ways of acheiving your goal:

    str = "C:/somepath/folder/file.txt"
    str = str.replace("\\", "/")

HTH, 

-Jay



More information about the Python-list mailing list