【问题标题】:Splitting a separated string to a dictionary but ignore the "equal" between double quotes, in Python在Python中将分隔的字符串拆分为字典但忽略双引号之间的“相等”
【发布时间】:2019-12-31 10:26:15
【问题描述】:

我有一个如下所示的字符串:

'username-localhost-8888="2|1:0|10:1575303827|23:username=|f29abfba56b3dc1d"; _ga=GA1.1.497472408.1576657799; name=psqakwfmvw'

Python 中是否有一个内置函数可以获取该字符串并构造一个字典,就像看起来像这样(忽略双引号的“比较”):

dict = {
    "username-localhost-8888": "2|1:0|10:1575303827|23:username-44:ZTY2YjcyYTMyNDk2=|f29abfba56b3dc1d",
    "_ga": "GA1.1.497472408.1576657799",
    "name": "psqakwfmvw"
}

我浏览了可用的模块,但似乎找不到任何匹配的内容。

【问题讨论】:

  • 你尝试过什么吗?看起来您想在分号上拆分,然后在每个部分中的 first 等于。
  • 您是否在解析 Cookie 标头?上下文就是一切。

标签: python string dictionary split


【解决方案1】:

你可以用.split做到这一点

input_str = 'username-localhost-8888="2|1:0|10:1575303827|23:username=|f29abfba56b3dc1d"; _ga=GA1.1.497472408.1576657799; name=psqakwfmvw'
output_dict = {}
# Note the space after `;`, this makes it so you don't get a space in the key
split_strings = input_str.split('; ')
for split_string in split_strings:
    # We only want to split once here since there can be multiple `=`
    key, value = split_string.split('=', maxsplit=1)
    output_dict[key] = value

【讨论】:

    【解决方案2】:

    对于str.split() 和理解来说,这似乎是一件容易的事:

    s='username-localhost-8888="2|1:0|10:1575303827|23:username=|f29abfba56b3dc1d"; _ga=GA1.1.497472408.1576657799; name=psqakwfmvw'
    dict([x.strip().split('=', maxsplit=1) for x in s.split(';')])
    

    这是一个概念证明:

    Python 3.7.5 (default, Dec 15 2019, 17:54:26) 
    [GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> s='username-localhost-8888="2|1:0|10:1575303827|23:username=|f29abfba56b3dc1d"; _ga=GA1.1.497472408.1576657799; name=psqakwfmvw'
    >>> dict([x.strip().split('=', maxsplit=1) for x in s.split(';')])
    {'username-localhost-8888': '"2|1:0|10:1575303827|23:username=|f29abfba56b3dc1d"', '_ga': 'GA1.1.497472408.1576657799', 'name': 'psqakwfmvw'}
    >>>
    

    【讨论】:

      【解决方案3】:

      你可以试试:

      output_dict = {}
      
      str_data = 'username-localhost-8888="2|1:0|10:1575303827|23:username=|f29abfba56b3dc1d"; _ga=GA1.1.497472408.1576657799; name=psqakwfmvw'
      list_data = str_data.split("; ")
      
      for single_list_data in list_data:
          key, val = single_list_data.split("=", 1)
          output_dict[key] = val
      
      print(output_dict)
      

      输出:

      {'username-localhost-8888': '"2|1:0|10:1575303827|23:username=|f29abfba56b3dc1d"', '_ga': 'GA1.1.497472408.1576657799', 'name': 'psqakwfmvw'}
      

      【讨论】:

        猜你喜欢
        • 2018-10-26
        • 2010-09-16
        • 2010-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-16
        相关资源
        最近更新 更多