Re: Iteration over strings
- From: Brett g Porter <bgporter@xxxxxxx>
- Date: Tue, 31 Jul 2007 14:17:14 -0400
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.
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"
>>> str
'C:\\somepath\\folder\\file.txt'
>>> str2 = str.replace('\\', '/')
>>> str2
'C:/somepath/folder/file.txt'
>>> str
'C:\\somepath\\folder\\file.txt'
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.
.
- Prev by Date: Re: standalone process to interact with the web
- Next by Date: Re: Iteration over strings
- Previous by thread: Re: Iteration over strings
- Next by thread: Re: Iteration over strings
- Index(es):
Relevant Pages
|