-3

我有一个返回以下内容的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 个新变量?

4

3 回答 3

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用于删除字符串之前/之后不需要的空格。

于 2013-02-14T12:28:51.623 回答
2

使用拆分功能:

my_string = #Contains ','
split_array = my_string.split(',')
于 2013-02-14T12:29:15.903 回答
0
result = myfunction()
result will be e.g. "192.168.200.123, 02/12/2013 13:59:42, 02/12/2013 13:59:42"

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

myfunction()中,返回一个list或一个tuplereturn (a, b, c)或返回[a, b, c]

或者,您可以使用以下s.split()功能:

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

您可以像这样进一步简化它:

result = my_function().split(',')
于 2013-02-14T16:07:33.497 回答