gpt4 book ai didi

python - 仅当字符串不紧跟在另一个特定字符之后时才在特定字符上拆分字符串

转载 作者:太空宇宙 更新时间:2023-11-04 10:37:38 26 4
gpt4 key购买 nike

我有以下代码行,它根据空白实例将字符串 data2 拆分为一个列表:

string_list = data2.split()

然而,在我的一些数据中,日期格式为 "28, Dec"。这里上面的代码在日期和月份之间的空白处拆分,而我不希望这样做。有没有一种方法可以说“在空白处拆分,但如果它在逗号之后则不行”?

最佳答案

您需要使用 regular expressions .

>>> re.split('(?<!,) ', 'blah blah, blah')
['blah', 'blah, blah']

来自链接:

(?<!...) Matches if the current position in the string is not preceded by a match for .... This is called a negative lookbehind assertion. Similar to positive lookbehind assertions, the contained pattern must only match strings of some fixed length. Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.

关于python - 仅当字符串不紧跟在另一个特定字符之后时才在特定字符上拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22547113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com