How to create raw string from string variable in python?

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

    My solution to convert string to raw string (works with this sequences only: '\a', \b', '\f', '\n', '\r', '\t', '\v' . List of all escape sequences is here):

    def str_to_raw(s):
        raw_map = {8:r'\b', 7:r'\a', 12:r'\f', 10:r'\n', 13:r'\r', 9:r'\t', 11:r'\v'}
        return r''.join(i if ord(i) > 32 else raw_map.get(ord(i), i) for i in s)
    

    Demo:

    >>> file_path = "C:\Users\b_zz\Desktop\fy_file"
    >>> file_path
    'C:\\Users\x08_zz\\Desktop\x0cy_file'
    >>> str_to_raw(file_path)
    'C:\\Users\\b_zz\\Desktop\\fy_file'
    

提交回复
热议问题