How to create raw string from string variable in python?

前端 未结 3 1513
时光说笑
时光说笑 2020-12-06 06:27

You create raw string from a string this way:

test_file=open(r\'c:\\Python27\\test.txt\',\'r\')

How do you create a raw variable from a str

3条回答
  •  不知归路
    2020-12-06 07:20

    There is no such thing as "raw string" once the string is created in the process. The "" and r"" ways of specifying the string exist only in the source code itself.

    That means "\x01" will create a string consisting of one byte 0x01, but r"\x01" will create a string consisting of 4 bytes '0x5c', '0x78', '0x30', '0x31'. (assuming we're talking about python 2 and ignoring encodings for a while).

    You mentioned in the comment that you're taking the string from the user (either gui or console input will work the same here) - in that case string character escapes will not be processed, so there's nothing you have to do about it. You can check it easily like this (or whatever the windows equivalent is, I only speak *nix):

    % cat > test < \x41
    heredoc> EOF
    % < test python -c "import sys; print sys.stdin.read()"
    \x41
    

提交回复
热议问题