gpt4 book ai didi

python - 使用python在多个空格上拆分字符串

转载 作者:太空宇宙 更新时间:2023-11-04 11:16:48 25 4
gpt4 key购买 nike

我想在多个空格而不是单个空格上拆分字符串。

我试过 string.split() 但它会在每个空格处拆分

这是我的代码

string='hi i am    kaveer  and i am a   student'   
string.split()

我预料到了结果

['嗨,我是','kaveer','我是','学生']

但实际结果是

['hi','i','am','kaveer','and','i','am','a','student']

最佳答案

您可以制作一个匹配 2 个或更多空格的正则表达式并使用 re.split()在比赛中 split :

import re

s='hi i am kaveer'
re.split(r'\s{2,}', s)

结果

['hi i am', 'kaveer']

关于python - 使用python在多个空格上拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56823117/

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