繁体   English   中英

Python:使用while循环遍历字符串

[英]Python: Iterate over string with while loop

我正在尝试删除最后一次出现“ +”之后的字符串末尾的所有字符。 因此,例如,如果我的字符串是“ Mother + why + is + the + river + laughing”,我想将其简化为“ Mother + why + is + the + river”。 我不知道字符串会是什么。

我想到了在字符串上向后迭代。 就像是:

while letter in my_string[::-1] != '+':
    my_string = my_string[:-1]

这是行不通的,因为未预定义字母。

有什么想法吗?

只需使用str.rsplit()

my_string = my_string.rsplit('+', 1)[0]

.rsplit()从字符串末尾分割; 限制为1,它将仅在字符串的最后+分割, [0]为您提供最后+之前的所有内容。

演示:

>>> 'Mother+why+is+the+river+laughing'.rsplit('+', 1)[0]
'Mother+why+is+the+river'

如果字符串中没有 + ,则返回原始字符串:

>>> 'Mother'.rsplit('+', 1)[0]
'Mother'

至于你的循环; 您正在针对反向字符串进行测试,条件返回True直到删除了最后一个+ 您必须在循环中测试您刚刚删除的字符:

while True:
    last = my_string[-1]
    my_string = my_string[:-1]
    if last == '+':
        break

但这与使用str.rsplit()相比效率很低; 为每个删除的字符创建一个新字符串非常昂贵。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM