string - python normalized path gets reset in a for loop -


I'm trying to get normalized paths on windows. Paths are stored in a list and I am looping them on as follows:

  & gt; & Gt; & Gt; Lst = ['C: \\', 'C: \\ Windows', 'C: \\ Program Files'] & gt; & Gt; & Gt; Lst ['C: \\', 'C: \\ Windows', 'C: \\ Program Files']> gt; & Gt; & Gt; Pst in lst: ... print pth ... C: \ C: \ Windows C: \ Program Files  

Note that it has removed a backslash from the output C: C: \.

Even if the path in the loop is normalized as below, the output does not change:

  gt; & Gt; & Gt; Import OS & gt; & Gt; & Gt; Pst in lst: ... print os.path.normpath (pth) ... C: \ C: \ Windows C: \ Program Files  

Can someone suggest a fix ? Thank you

Update

The suggestion about raw strings seems like a better way to handle it. But how to specify the string within the loop as a raw string Example:

  for pst in lst: raw_str = rpth  

clearly Does not work above. How do I achieve this? Rpath / to / file '?

Double slash is the escape string - you need to run the string before the slash loop in string literals lst [0] will print, without slash. If you really want to include a double slash in your literal, use the raw string syntax:

  gt; & Gt; Lst = ['C: \\', 'C: \\ Windows', 'C: \\ Program Files'] & gt; & Gt; & Gt; Lst [0] 'C: \\' & gt; & Gt; & Gt; Print List [0] C: \ & gt; & Gt; & Gt; Lst2 = [r'C: \\ ', r'C: \\ Windows', r'C: \\ Program Files']> gt; & Gt; & Gt; Lst2 [0] 'C: \\\\' & gt; & Gt; & Gt; Print List 2 [0] C: \\  

Edit: If you want repeat the slash, you have a simple string Replace can:

  & gt; & Gt; & Gt; X = 'C: \\ Windows' & gt; & Gt; & Gt; Print xc: \ windows & gt; & Gt; & Gt; X = x.replace ('\\', '\\\\') & gt; & Gt; & Gt; Print x c: \\ Windows  

Comments

Popular posts from this blog

sql - dynamically varied number of conditions in the 'where' statement using LINQ -

asp.net mvc - Dynamically Generated Ajax.BeginForm -

Debug on symbian -