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..
CodePudding user response:
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)
CodePudding user response:
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.