Python将变量视为文字/原始字符串 [英] Python treat variable as literal/raw string

查看:520
本文介绍了Python将变量视为文字/原始字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不认为将变量视为原始字符串很难!我搜索并发现了类似的问题,但没有适当的答案.

I can't believe it's that difficult to treat a variable as a raw string! I have searched and found questions alike, but no proper answer.

我有一个存储域名的变量,例如域\用户",我只需要使用re来获取用户名.问题是Python为我提供了特殊字符组合的十六进制值,例如当我在字符串中有\b时.

I have a variable with domain name stored in. e.g. 'domain\user', I need to get the username only using re. The problem is Python gives me hex values for special character combinations, for example when I have \b in the string.

我只需要从变量中获取文字字符串,就别无所求了.

I just need to get the literal string from the variable, and nothing else.

author = list[0] // list[0] contains 'domain\blah'
author = re.sub('.*\\\\(.+)$', r'\1', author)

我希望blah得到'domain\x08lah'

在开头不要将字符串保存为原始字符串,因为我是从其他正则表达式操作中获取字符串的.

Saving the string as raw string at the start is not an option, because I'm getting the string from other regex operations.

有什么想法吗?

我误以为该变量使用单斜杠.实际上,当从另一个操作获取该变量时,反斜杠已经被转义了.因此,在尝试创建测试方案时,这对我来说是个问题.

I was mistaken by assuming the variable had a single slash in. In fact, when getting the variable from another operation, the backclash had already been escaped. So I was making it a problem for myself when trying to create a test scenario.

推荐答案

原始字符串文字仅通过避免(大多数)常规字符串文字会使用的字符串转义码而仅用于创建字符串值使用.

A raw string literal is only used to create string values, by avoiding (most) string escape codes that a regular string literal would use.

您的字符串\x08字符开头;它从不包含反斜杠和b字符.如果使用字符串文字定义了list[0]中包含的值,则您忘记了转义反斜杠.如果数据来自其他地方,则您正在查看的原始十六进制字节值为08:

Your string started with the \x08 character; it never contained a backslash and a b character. If you defined the value contained in list[0] with a string literal, you forgot to escape the backslash. If the data came from somewhere else, you are looking at a raw hex byte value of 08:

>>> list_0 = 'domain\x08lah'
>>> list_0[6]
'\x08'
>>> len(list_0[6])
1
>>> ord(list_0[6])
8

如果该字节原本是两个字符,则可以使用字符串替换来修复数据:

If this byte was meant to be two characters instead, you could repair the data with string replacement:

>>> list_0.replace('\b', '\\b')
'domain\\blah'

这篇关于Python将变量视为文字/原始字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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