问题描述
elements = ['abc\n','def\t']
我想获得 raw string 的长度,即在它编译转义字符之前。如果它们在单个变量中,我知道该怎么做,例如:
org = 'abc\n' # Original string
len(org) # Will give 4
raw = r'abc\n' # Raw string
len(raw) # Will give 5 as it counts the \n as 2 chars
我试过这样做,但它不起作用,任何帮助将不胜感激。
for e in elements:
print(len(e)) # Gives length of compiled string
print(len(re)) # Throws error
print(len(r+e)) # Throws error
谢谢
解决方法
您可以尝试使用 'unicode_escape' 对字符串进行编码以获得所需的结果
代码:
elements = ['abc\n','def\t']
for e in elements:
print(len(e.encode("unicode_escape")))
输出:
5
5