【问题标题】:how to split a python string如何拆分python字符串
【发布时间】:2013-02-14 12:28:25
【问题描述】:

我有一个 python 函数,它返回以下内容:

result = myfunction()
result will be e.g. "192.168.200.123, 02/12/2013 13:59:42, 02/12/2013 13:59:42"

即包含 3 个以逗号分隔的值的字符串。

如何将此字符串拆分为 3 个新变量?

【问题讨论】:

标签: python


【解决方案1】:

使用拆分功能:

my_string = #Contains ','
split_array = my_string.split(',')

【讨论】:

    【解决方案2】:
    >>> s = "192.168.200.123, 02/12/2013 13:59:42, 02/12/2013 13:59:42"
    >>> n = [e.strip() for e in s.split(',')]
    >>> print n
    ['192.168.200.123', '02/12/2013 13:59:42', '02/12/2013 13:59:42']
    

    n 现在是一个包含三个元素的列表。如果您知道您的字符串将被精确地拆分为三个变量并且您想命名它们,请使用:

    a, b, c = [e.strip() for e in s.split(',')]
    

    strip 用于删除字符串前后不需要的空格。

    【讨论】:

      【解决方案3】:
      result = myfunction()
      result will be e.g. "192.168.200.123, 02/12/2013 13:59:42, 02/12/2013 13:59:42"
      

      解决这个问题的两种方法:

      myfunction() 中,返回listtuplereturn (a, b, c) 或返回[a, b, c]

      或者,您可以使用s.split() 函数:

      result = my_function()
      results = result.split(',')
      

      你可以像这样进一步简化:

      result = my_function().split(',')
      

      【讨论】:

        猜你喜欢
        • 2010-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        相关资源
        最近更新 更多