gpt4 book ai didi

Python3如何分隔元组中的项目

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

list1 = 'it is, a good,day'

我需要用逗号分隔字符串的所有部分:'it is''a good''day' 然后将 'ouf' 放在每个部分之间,这样它就可以打印 it is ouf a good ouf day

注意 ' 处逗号后的空格,好' 还有没有办法只删除逗号后的空格?

最佳答案

您可以使用 split , strip , joinmap

>>> list1 = 'it is, a good,day'
>>> ' ouf '.join(map(str.strip,list1.split(',')))
'it is ouf a good ouf day'

或者您可以尝试 replace

>>> list1.replace(', ',',').replace(',',' ouf ')
'it is ouf a good ouf day'

考虑到编辑,我建议 re模块的 sub功能。

>>> re.sub(r',\s?',' ouf ',list1)
'it is ouf a good ouf day'

关于Python3如何分隔元组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30141867/

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