So let's say I have a string, like this:
string = '12345 67890'
I want to go back to search for that plus, and add a letter 'H', so the end result would be like this:
string = '12345 h67890
Also, what if I want to get the latest , so if there is two 's, I want to get the last ?
Any help would be appreciated!
CodePudding user response:
You could use reverse split to split on the last instance of , then join with H:
>>> ' H'.join('123 456 789'.rsplit(' ',1))
'123 456 H789'
CodePudding user response:
Convert into list, iterate through list, when you find the plus add an 'h' into the next index.
string = '12345 67890'
stringList = list(string)
i = 0
newString = ''
for i in range(len(stringList)):
if stringList[i] == ' ':
stringList.insert(i 1,'h')
for letter in stringList:
newString = letter
print(newString)
CodePudding user response:
Since you asked how to do it with if
statements:
i = -1
for i in range(len(my_str)):
if my_str[i] == ' ':
plus = i 1 # <- will update every time you see a symbol
if i != -1:
my_str = my_str[:i] 'h' my_str[i:]
Alternatively, you can search backwards:
i = -1
for i in reversed(range(len(my_str))):
if my_str[i] == ' ':
plus = i 1 # <- will update every time you see a symbol
break
if i != -1:
my_str = my_str[:i] 'h' my_str[i:]
As others have mentioned you can use built-in functions like find
and rfind
. My personal choice is to refer to regular expressions for this type of thing:
import re
my_str = re.sub('(.*\ )(.*)',r"\1h\2", my_str))