'How can I add a if statement that goes back in string if there is a number, and to stop if there is something other than a number?

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!



Solution 1:[1]

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)

Solution 2:[2]

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))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MatWDS
Solution 2 ramzeek