Re: Iteration over strings
- From: Jay Loden <python@xxxxxxxxxxxx>
- Date: Tue, 31 Jul 2007 14:07:05 -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.
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
.
- Prev by Date: Re: Encryption recommendation
- Next by Date: Re: standalone process to interact with the web
- Previous by thread: Error with Tkinter and tkMessageBox
- Next by thread: Re: Iteration over strings
- Index(es):
Relevant Pages
|