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

后端 未结 11 969
后悔当初
后悔当初 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

    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.

提交回复
热议问题