Iteration over strings
Brett g Porter
bgporter at acm.org
Tue Jul 31 20:17:14 CEST 2007
Robert Dailey wrote:
> 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.
The thing that you need to remember is that strings in Python never
change (and nothing ever changes that).
Any time that you start out thinking "I need to change this string' you
need to immediately translate that thought into "I need to create a new
string with some changes made to this string".
String objects can already do what you're trying to do here:
>>> str = "C:\\somepath\\folder\\file.txt"
>>> str2 = str.replace('\\', '/')
replace() returns a new string with all instances of the 1st subsstring
replaced with the second substring -- note that the original string
'str' is unmodified.
Also note that if this is your actual use case, the standard lib also
contains a function os.path.normpath() that does all the correct
manipulations to correctly normalize file paths on the current platform.
More information about the Python-list