简体   繁体   English

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

[英]How can i convert specific characters in a string and in a specific index

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".例如,我有字符串“alba iuliara”,我想做的是将所有“a”转换为“A”,但不是第一个和最后一个“a”。 The result must be "albA iuliAra"结果必须是“albA iuliAra”

Any idea how can i do that using a statement like while, if and etc..知道如何使用诸如 while、if 等语句来做到这一点。

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)
        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.我使用了@jock 逻辑,但进行了修改以使其通用。

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

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