How to create raw string from string variable in python?

前端 未结 3 1511
时光说笑
时光说笑 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:15

    The solution by ndpu works for me.

    I could not resist the temptation to enhance it (make it compatible with ancient Python 2 versions and hoping to speed it up):

    _dRawMap = {8:r'\b', 7:r'\a', 12:r'\f', 10:r'\n', 13:r'\r', 9:r'\t', 11:r'\v'}
    
    def getRawGotStr(s):
        #
        return r''.join( [ _dRawMap.get( ord(c), c ) for c in s ] )
    

    I did a careful time trial, and it turns out that the original code by ndpu is a little faster. List comprehensions are fast, but generator expressions are faster.

提交回复
热议问题