如何在第一次出现后用符号替换所有字符而不影响大小写?

2024-10-06 07:40:39 发布

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

我不知道如何替换第一个字符的所有事件,不包括第一个字符而不影响最初的大小写。例如,我想把她变成海上最棒的,她在$ea上是$t。做这件事最有效的方法是什么

我尝试过使用.title()但没有成功,并且收到了错误字符大小写的拙劣输出

def change(s):
    news=s.lower()
    firstchar=news[0]
    modifieds=news[1:].replace(firstchar,"$")
    final=(firstchar+modifieds)
    print(final.title())

change("She's The Best On The Sea")

她在$Ea上的$T是$T


Tags: the方法titledef错误事件change字符
2条回答

以可读的方式:

text = "She's The Best On The Sea"

new_text = ""
string_to_check = "s"
replacement = "$"

for i in range(len(text)):
    if i != 0 and text[i].lower() == string_to_check:
        new_text += replacement
    else:
        new_text += text[i]

print(new_text)

输出:

She'$ The Be$t On The $ea

re.subre.IGNORECASE一起使用:

import re

s = "She's The Best On The Sea"
s[0] + re.sub('s', '$', s[1:], flags=re.IGNORECASE)

输出:

"She'$ The Be$t On The $ea"

相关问题 更多 >