如何从python中的字符串变量创建原始字符串? [英] How to create raw string from string variable in python?

查看:38
本文介绍了如何从python中的字符串变量创建原始字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以通过这种方式从字符串创建原始字符串:

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 string variable, such as

path = 'c:\Python27\test.txt'

test_file=open(rpath,'r')

因为我有一个文件路径:

Because I have a file path:

file_path = "C:\Users\b_zz\Desktop\my_file"

当我这样做时:

data_list = open(os.path.expandvars(file_path),"r").readlines()

我得到:

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    scheduled_data_list = open(os.path.expandvars(file_path),"r").readlines()
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Users\x08_zz\\Desktop\\my_file'

推荐答案

一旦在流程中创建了字符串,就没有原始字符串"这样的东西.""r"" 指定字符串的方式仅存在于源代码本身中.

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.

这意味着 "\x01" 将创建一个由 0x01 组成的字符串,但是 r"\x01" 将创建一个字符串由 4 个字节组成 '0x5c', '0x78', '0x30', '0x31'.(假设我们在谈论 python 2 并暂时忽略编码).

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).

您在评论中提到您要从用户那里获取字符串(gui 或控制台输入在这里的工作方式相同) - 在这种情况下,将不会处理字符串字符转义,因此您无需做任何处理它.您可以像这样轻松检查它(或任何等效的 Windows,我只说 *nix):

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 <<EOF                                             
heredoc> \x41
heredoc> EOF
% < test python -c "import sys; print sys.stdin.read()"
\x41

这篇关于如何从python中的字符串变量创建原始字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆