gpt4 book ai didi

python - 在分隔符处拆分 python 字符串,但在特定分隔符处

转载 作者:太空狗 更新时间:2023-10-30 01:44:08 24 4
gpt4 key购买 nike

有没有一种方法可以在不使用 for 循环的情况下拆分 python 字符串,该循环基本上将中间的字符串拆分到最接近的定界符。

喜欢:

The cat jumped over the moon very quickly.

分隔符是空格,结果字符串是:

The cat jumped over
the moon very quickly.

我看到有一个 count,我可以在其中看到有多少空格(虽然看不到如何返回它们的索引)。然后我可以通过除以 2 找到中间的那个,但是然后如何在这个索引处的这个分隔符上说 split 。 Find 很接近,但它返回第一个索引(或使用 rfind 的右第一个索引)而不是所有找到“”的索引。我可能想多了。

最佳答案

这应该有效:

def split_text(text):
middle = len(text)//2
under = text.rfind(" ", 0, middle)
over = text.find(" ", middle)
if over > under and under != -1:
return (text[:,middle - under], text[middle - under,:])
else:
if over is -1:
raise ValueError("No separator found in text '{}'".format(text))
return (text[:,middle + over], text[middle + over,:])

它没有使用 for 循环,但使用 for 循环可能会有更好的性能。

我通过引发错误来处理在整个字符串中找不到分隔符 的情况,但是更改 raise ValueError() 以实现您想要处理的任何方式案件。

关于python - 在分隔符处拆分 python 字符串,但在特定分隔符处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54298939/

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