使用Python中的字符串令牌拆分字符串而不是字符令牌

2024-04-26 10:13:40 发布

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

我有一个字符串,比如:

10-24-2017 10:09:18.218 - my_test - INFO - My Automation version 0.0.1

我希望用标记" - "(注意前面和后面的空格)分割字符串。上面的字符串应该拆分为:

{'10-24-2017 10:09:18.218', 'my_test', 'INFO', 'My Automation version 0.0.1'}

如果我只是用“-”分开,那么日期字符串也会被分开,我不想这样做。有人能给我指出正确的方向吗?你知道吗

谢谢


Tags: 字符串标记testinfoversionmy方向automation
3条回答

你可以使用普通的分割函数。你知道吗

test_str = "10-24-2017 10:09:18.218 - my_test - INFO - My Automation version 0.0.1"

print(test_str.split(' - '))

输出:

['10-24-2017 10:09:18.218', 'my_test', 'INFO', 'My Automation version 0.0.1']

您可以改用re.split

In [3]: re.split(' - ', '123-456 - foo - bar')
Out[3]: ['123-456', 'foo', 'bar']

或者被整根绳子分开:

In [5]: '123-456 - foo - bar'.split(' - ')
Out[5]: ['123-456', 'foo', 'bar']
'10-24-2017 10:09:18.218 - my_test - INFO - My Automation version 0.0.1'.split(' - ')

相关问题 更多 >