0

I am new to python and am starting to work with regular expressions and was wondering if it is possible to use the r prefix with a string variable? For example, I know if I have:

r'\\XY123/data\sheet\file1.xlsm'

This works. But is it possible to do something like this?

path_list =['\\XY123/data\sheet\file1.xlsm','\\XY123/data\sheet\file2.xlsm']
r + path_list[1]

I am going to be looping through a list of file path names and without the r prefix I am not catching everything I need. A code snippet:

path_list =['\\XY123/data\sheet\file1.xlsm','\\XY123/data\sheet\file2.xlsm']
for v in path_list:
    vbaparser = VBA_Parser(v)

I would need the r prefix in VBA_Parser():

    vbaparser = VBA_Parser(r+v)?? (I know this is wrong)

Any help is greatly appreciated!

Steven
  • 11
  • 2
  • 2
    Why not use `path_list =[r'\\XY123/data\sheet\file1.xlsm',r'\\XY123/data\sheet\file2.xlsm']`? – Wiktor Stribiżew Nov 30 '15 at 21:28
  • One thing I didn't mention is that I am reading in a csv and I am taking one of the columns that contains all of these path names. path_list = newdata[key].tolist() – Steven Nov 30 '15 at 21:34
  • This isn't exactly a duplicate of that question, but it explains what the `r` prefix is, which explains why `"\\XY123/..."` is not the same as `r"\\XY123/.."` and therefore doesn't create the same output – Adam Smith Nov 30 '15 at 21:35
  • So why is this a duplicate if "this isn't exactly a duplicate"? I understand that "\\XY123/..." is not the same as r"\\XY123/.." , as well as what the `r` prefix is, but my question was how to use `r` with a variable that is a string, not about what the `r` and `u` prefixes are? – Steven Nov 30 '15 at 21:40
  • @Steven, this is actually a good question, there are related questions but a lot suggest string-escape that does not always work, this old recipe should do the job http://code.activestate.com/recipes/65211-convert-a-string-into-a-raw-string. Also `vbaparser = VBA_Parser(r"{}".format(v))` won't work – Padraic Cunningham Nov 30 '15 at 21:45
  • 1
    @Padraic Cunningham Thank you I will take a look! – Steven Nov 30 '15 at 21:51
  • @Steven with respect, if you understood what the `r` prefix did, you wouldn't be asking how to use it with a non-literal string. `r'some string'` is a raw string literal. It's just a shortcut to avoid escaping your backslashes. In something that's already a string, those backslashes are *already* escaped so it's unnecessary. `r'\\something'` == `'\\\\something'`. – Adam Smith Nov 30 '15 at 22:10
  • @Steven w.r.t. your comment that it's being read from a csv, perhaps you have leading or trailing spaces that you're failing to strip off? Regardless, the raw string literal notation is irrelevant to a discussion of non-literal strings :) – Adam Smith Nov 30 '15 at 22:12

0 Answers0