Print raw string from variable? (not getting the answers)

后端 未结 11 911
后悔当初
后悔当初 2020-12-04 10:14

I\'m trying to find a way to print a string in raw form from a variable. For instance, if I add an environment variable to Windows for a path, which might look like \'

相关标签:
11条回答
  • 2020-12-04 10:47

    You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.

    0 讨论(0)
  • 2020-12-04 10:47

    Your particular string won't work as typed because of the escape characters at the end \", won't allow it to close on the quotation.

    Maybe I'm just wrong on that one because I'm still very new to python so if so please correct me but, changing it slightly to adjust for that, the repr() function will do the job of reproducing any string stored in a variable as a raw string.

    You can do it two ways:

    >>>print("C:\\Windows\Users\alexb\\")
    
    C:\Windows\Users\alexb\
    
    >>>print(r"C:\\Windows\Users\alexb\\")
    C:\\Windows\Users\alexb\\
    

    Store it in a variable:

    test = "C:\\Windows\Users\alexb\\"
    

    Use repr():

    >>>print(repr(test))
    'C:\\Windows\Users\alexb\\'
    

    or string replacement with %r

    print("%r" %test)
    'C:\\Windows\Users\alexb\\'
    

    The string will be reproduced with single quotes though so you would need to strip those off afterwards.

    0 讨论(0)
  • 2020-12-04 10:47

    Replace back-slash with forward-slash using one of the below:

    • re.sub(r"\", "/", x)
    • re.sub(r"\", "/", x)
    0 讨论(0)
  • 2020-12-04 10:52

    i wrote a small function.. but works for me

    def conv(strng):
        k=strng
        k=k.replace('\a','\\a')
        k=k.replace('\b','\\b')
        k=k.replace('\f','\\f')
        k=k.replace('\n','\\n')
        k=k.replace('\r','\\r')
        k=k.replace('\t','\\t')
        k=k.replace('\v','\\v')
        return k
    
    0 讨论(0)
  • 2020-12-04 10:54

    Just simply use r'string'. Hope this will help you as I see you haven't got your expected answer yet:

        test = 'C:\\Windows\Users\alexb\'
        rawtest = r'%s' %test
    
    0 讨论(0)
  • 2020-12-04 11:00

    I know i'm too late for the answer but for people reading this I found a much easier way for doing it

    myVariable = 'This string is supposed to be raw \'
    print(r'%s' %myVariable)
    
    0 讨论(0)
提交回复
热议问题