【问题标题】:Regex for splitting a string which contains commas用于拆分包含逗号的字符串的正则表达式
【发布时间】:2014-02-28 09:02:00
【问题描述】:

如何在 Python 中用逗号分割字符串,其中包含逗号本身?假设字符串是:

object = """{"alert", "Sorry, you are not allowed to do that now, try later", "success", "Welcome, user"}"""

如何确保拆分后只得到四个元素?

【问题讨论】:

  • object = {} 是否也包含在字符串中?
  • 只有 {}。但我可以轻松剥离它们。

标签: python string split comma


【解决方案1】:
>>> from ast import literal_eval
>>> obj = '{"alert", "Sorry, you are not allowed to do that now, try later", "success", "Welcome, user"}'
>>> literal_eval(obj[1:-1])
('alert', 'Sorry, you are not allowed to do that now, try later', 'success', 'Welcome, user')

On Python3.2+ 你可以直接使用literal_eval(obj)

【讨论】:

  • 工作就像一个魅力。谢谢。
  • @thefourtheye,根据快速测试,Python 2.7 抛出 ValueError,而 Python 3.3 识别它。
【解决方案2】:
>>> import re
>>> re.findall(r'\"(.+?)\"', obj)
['alert', 'Sorry, you are not allowed to do that now, try later',
 'success', 'Welcome, user']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多