Home > Software engineering >  Find what character appears next to a specified other in python
Find what character appears next to a specified other in python

Time:05-10

I’m coding in python. Is there a way to find what appears next to a specified other character. My string is A4B6C1D7. Using the code: if “A” in string:I would like to know if there is a way to then find out what appears next to it, so ideally: yes it appears in string and the number next to it is 4. It will always be a number next to the letter before another letter if this helps? Thanks!

CodePudding user response:

You can use .find() method of string to find where in the string the character lies. You can then pull the next character by adding one to that:

myString = 'A4B6C1D7'
print(myString[myString.find('A') 1])

>>>'4'

CodePudding user response:

Assuming there are no multiple instances of "A" for example:

def get_value(char, full):
    if char in full:
        index = full.index(char)
        if index   1 <= len(full) - 1:
            return full[index 1]

print(get_value("A", "A4B6C1D7"))
# 4

CodePudding user response:

Something like this i think:

myString = 'A4B6C1D7'
if 'A' in myString:
    ind = myString.index('A')
    nextLet = myString[ind 1:ind 2]
    print(nextLet)
  • Related