[英]How can i convert specific characters in a string and in a specific index
例如,我有字符串“alba iuliara”,我想做的是將所有“a”轉換為“A”,但不是第一個和最后一個“a”。 結果必須是“albA iuliAra”
知道如何使用諸如 while、if 等語句來做到這一點。
如果您使用替換方法,這很容易。
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
我使用了@jock 邏輯,但進行了修改以使其通用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.