如何替换字符串Python中的第二次迭代

2024-09-28 13:18:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从字符串中删除一个单词,但前提是它是第二个单词。举个例子:

我试过脱衣换新。切片不起作用,因为Preds可能每次都不在同一个地方

# Complete the function to remove the word PREDS from the given string
# ONLY if it's not the first word and return the new string
def removePREDS(mystring):
    return mystring.replace("PREDS", ' ')

# expected output: PREDS Rocks
print(removePREDS('PREDS Rocks'))

# expected output: Hello, John
print(removePREDS('Hello, PREDSFan'))

我可以删除pred和第一个,但不知道如何删除第二个


Tags: the字符串hellooutputstringreturn单词word
1条回答
网友
1楼 · 发布于 2024-09-28 13:18:13

功能:

def remove_if_not_starts_from(src, substr):
    return src if src.startswith(substr) else src.replace(substr, '')

用法:

str1 = 'Lorem ipsum'
str2 = 'ipsum Loremipsum'
word = 'Lorem'

print('{} -> {}'.format(str1, remove_if_not_starts_from(str1, word)))
print('{} -> {}'.format(str2, remove_if_not_starts_from(str2, word)))

输出:

Lorem ipsum -> Lorem ipsum
ipsum Loremipsum -> ipsum ipsum

相关问题 更多 >

    热门问题