Re: Iteration over strings



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.

.



Relevant Pages

  • Re: Documentation for "str()" could use some adjustment.
    ... there's no mention of the fact that "str" of a Unicode string ... | documentation (and several Python books) seem to indicate that "str" will ...
    (comp.lang.python)
  • Re: ISAM error when trying to create tablelink
    ... Dim tDef As DAO.TableDef ... Doug Steele, Microsoft Access MVP ... Dim str As String ...
    (microsoft.public.access.modulesdaovba)
  • Re: Using the Dictionary object
    ... Private Sub LV_ItemCheck ... Dim Str As String ... MyNext = MyNext - 1 ...
    (microsoft.public.excel.programming)
  • Re: List problem
    ... Now the problem, reading through the Python tutorial's, it describe's ... Then the error returned is that 'str' and 'list' could not be ... How can they have the string 'bacon' and have it returned with no ... Your error message doesn't match your command. ...
    (comp.lang.python)
  • Documentation for "str()" could use some adjustment.
    ... The Python documentation for "str" says ... Return a string containing a nicely printable representation of an object." ... there's no mention of the fact that "str" of a Unicode string ...
    (comp.lang.python)