Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

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

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 'C:\WindowsUsersalexb', I know I can do:

print(r'C:\WindowsUsersalexb')

But I cant put an r in front of a variable.... for instance:

test = 'C:\WindowsUsersalexb'
print(rtest)

Clearly would just try to print rtest.

I also know there's

test = 'C:\WindowsUsersalexb'
print(repr(test))

But this returns 'C:\Windows\Usersx07lexb' as does

test = 'C:\WindowsUsersalexb'
print(test.encode('string-escape'))

So I'm wondering if there's any elegant way to make a variable holding that path print RAW, still using test? It would be nice if it was just

print(raw(test))

But its not

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.

Two ways of solving it:

  1. Get the path you want using native python functions, e.g.:

    test = os.getcwd() # In case the path in question is your current directory
    print(repr(test))
    

    This makes it platform independent and it now works with .encode. If this is an option for you, it's the more elegant solution.

  2. If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...