在Python中的字符串中处理转义序列 [英] Process escape sequences in a string in Python

查看:316
本文介绍了在Python中的字符串中处理转义序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,当我从文件或用户获取输入时,我会得到一个带有转义序列的字符串。我想处理转义序列的方式与Python处理字符串中的转义序列相同文字

Sometimes when I get input from a file or the user, I get a string with escape sequences in it. I would like to process the escape sequences in the same way that Python processes escape sequences in string literals.

例如,假设 myString 定义为:

>>> myString = "spam\\neggs"
>>> print(myString)
spam\neggs

我想要一个函数(我会调用它进程)执行此操作:

I want a function (I'll call it process) that does this:

>>> print(process(myString))
spam
eggs

重要的是函数可以处理Python中的所有转义序列(在上面链接的表中列出)。

It's important that the function can process all of the escape sequences in Python (listed in a table in the link above).

Python是否具有这样的功能?

Does Python have a function to do this?

推荐答案

正确的做法是使用'string-escape'代码解码字符串。

The correct thing to do is use the 'string-escape' code to decode the string.

>>> myString = "spam\\neggs"
>>> decoded_string = bytes(myString, "utf-8").decode("unicode_escape") # python3 
>>> decoded_string = myString.decode('string_escape') # python2
>>> print(decoded_string)
spam
eggs

不要使用AST或EVAL。使用字符串编解码器更安全。

Don't use the AST or eval. Using the string codecs is much safer.

这篇关于在Python中的字符串中处理转义序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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