多行字符串文本解析

2024-03-28 23:09:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python的交互式控制台中尝试了以下操作:

>>> """"string"""
'"string'
>>> """"string""""
SyntaxError: EOL while scanning string literal

我希望后一个例子""""string""""返回{},因为我在开头有三个引号,在结尾有三个引号。Python如何解释它?在


Tags: string结尾引号例子whileliteraleolscanning
2条回答

Python将其解释为:

 """"string""" "                                                                                                                   "
#^^^These three " to start the string literal. The next one counts in the string.
#The three last ones after the last one are counted as the end.

注意偏离的"

你只需:

^{pr2}$

它看到三重引号的字符串""""string""",后面是一个非三重引号的字符串,它不能在EOL完成,"

tokenize模块可以向您显示它在做什么:

s = '""""string""""'
g = tokenize.generate_tokens(io.StringIO(s).readline)
t = list(g)
print(t)

这将打印带有'""""string"""'的字符串标记,然后打印带有'"'的错误令牌。

一般来说,当你不知道如何解释the grammar(我想你先看一下语法)时,回答这样的问题的最佳方法是什么是使用tokenize、ast和friends。

相关问题 更多 >