如何在字符串和特定索引中转换特定字符

发布于 2025-02-11 07:59:40 字数 117 浏览 1 评论 0原文

例如,我有“ alba iuliara”字符串,我想做的是用“ a”转换所有“ a”,但不是第一个和最后一个“ a”。结果必须是“ alba iuliara”,

任何想法如何使用诸如时期,如果和等等的陈述。

For example i have the string "alba iuliara" and what i want to do is to convert all the "a" with "A" but not the first and the last "a". The result must be "albA iuliAra"

Any idea how can i do that using a statement like while, if and etc..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

山人契 2025-02-18 07:59:40

如果您使用替换方法,这很容易。

代码,如果您不考虑第一个和最后一个字符

your_string = "alba iuliara"
your_string = f"{your_string[0]}{your_string[1:-1].replace('a','A')}{your_string[-1]}"
print(your_string)

It's pretty easy if you use the replace method.

Code if you don't consider the first and last characters

your_string = "alba iuliara"
your_string = f"{your_string[0]}{your_string[1:-1].replace('a','A')}{your_string[-1]}"
print(your_string)
指尖凝香 2025-02-18 07:59:40
        your_string = "Namaskara"
        rep_char='a'
        occ1=your_string.find(rep_char)   #Searches for first occurence of replacing character
        occn=your_string.rfind(rep_char) #Searches for last occurence of replacing character
    
    #from startig poition of string to your first occurence of character  and last occurence of character to end of the string nothing will be replaced. for remaining string character will be replaced with uppercase
        your_string = f"{your_string[0:occ1+1]}{your_string[occ1+1:occn].replace(rep_char,rep_char.upper())}{your_string[occn:]}"
    
        print(your_string)

output: NamAskAra

我已经使用了@Jock逻辑,但已修改以使其通用。

        your_string = "Namaskara"
        rep_char='a'
        occ1=your_string.find(rep_char)   #Searches for first occurence of replacing character
        occn=your_string.rfind(rep_char) #Searches for last occurence of replacing character
    
    #from startig poition of string to your first occurence of character  and last occurence of character to end of the string nothing will be replaced. for remaining string character will be replaced with uppercase
        your_string = f"{your_string[0:occ1+1]}{your_string[occ1+1:occn].replace(rep_char,rep_char.upper())}{your_string[occn:]}"
    
        print(your_string)

output: NamAskAra

I have used @jock logic but modified to make it generic.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文