Home > Software design >  Getting position based on the letter
Getting position based on the letter

Time:05-13

Hello this is a little complicated question. I hope you can understand what I'm trying to ask. Let's say I have:

newvar = hoavyeph8

There is an 'e' in this var. I want to know which letter is present before e and write the 'if' function. Like:

if I is present before e:
  do something

Like this. I want to know the letter present behind the another letter. And write the function. How can I?

CodePudding user response:

newvar = "hoavyeph8"

for index, c in enumerate(newvar):
  if(c=="e"):
    print(f"{newvar[index-1]} is before e")

This will tell you what is before e, I'm not sure what you want to do next.

CodePudding user response:

I'd recommend first reading TheRavenSpectre's answer, as that is perfectly adequate. If you want to see other ways, continue reading.

What you are asking can be solved two ways: using the find() function, or using regex (regular expressions). Regex will needlessly complicate it, while find() is perfectly adequate here.

Using find(), you can do it two ways, depending if you are only looking for one type of preceding letter or multiple (only i before e, or also a before e). To look for multiple letters:

newvar = "this is a test string"
# search for where s is preceded by a space
i = newvar.find('s')
while i != -1:
    if i > 0 and newvar[i - 1] == ' ': # first test that the index of s is not zero so it does not look outside the string
        doSomething(newvar, i - 1)
    i = newvar.find('s', i 1)

The other case would be to only look for i before e. That can be solved as such: string = "I want you to find the i before e, siE vIe"

j = string.lower().find('ie')
while j != -1:
    doSomething(string, j)
    j = string.lower().find('ie', j 1)

This code would look for all occurrences of 'ie', regardless of case, perform the operation, then continue looking.

  • Related