中处理字符串中的转义序列

中处理字符串中的转义序列

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

问题描述

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

例如,假设 myString 定义为:

>>>myString = "垃圾邮件\neggs">>>打印(我的字符串)垃圾邮件否定

我想要一个执行此操作的函数(我将其称为 process):

>>>打印(进程(myString))垃圾邮件蛋

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

Python 有函数可以做到这一点吗?

解决方案

正确的做法是使用字符串转义"代码来解码字符串.

>>>myString = "垃圾邮件\neggs">>>decode_string = bytes(myString, "utf-8").decode("unicode_escape") # python3>>>decode_string = myString.decode('string_escape') # python2>>>打印(解码字符串)垃圾邮件蛋

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

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.

For example, let's say myString is defined as:

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

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

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

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

Does Python have a function to do this?

解决方案

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

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

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

08-04 12:36