Python shlex Spli

2024-04-26 21:10:06 发布

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

多亏了shlex这种绳子我想分开:

str = 'This doesn''t work' 54e+5 15 .FALSE. 'Another example of "test"'

预期结果:

  • 这不管用
  • 54e+5号
  • 十五
  • 。错误。在
  • “测试”的另一个例子

我的主要问题是语法在带引号的字符串中使用双简单引号“”。 我不能让shlex上班。我尝试了以下设置:

^{pr2}$

但即使没有空格字符,它也会在“”之间拆分。在

谢谢你!!在


Tags: oftestfalseexample错误语法anotherthis
1条回答
网友
1楼 · 发布于 2024-04-26 21:10:06

理想情况下,如果您控制文本是如何生成的,我会将文件写为CSV,并允许CSV模块正确地引用项目。然后再把它读回一个列表中就很容易了。在

但鉴于文本本身,如何:

In [4]: import shlex
In [6]: text = """'This doesn''t work' 54e+5 15 .FALSE. 'Another example of "test"'"""
In [34]: [item.replace('\\"\\"',"''") for item in shlex.split(text.replace("''",'\\"\\"'))]
Out[34]: ["This doesn''t work", '54e+5', '15', '.FALSE.', 'Another example of "test"']

相关问题 更多 >