Home > database >  print words with a in 3th position in the loops
print words with a in 3th position in the loops

Time:10-23

I am doing print the words that have in the 3th position, the letter a..


for w in df['names_mother']:
    if w[2]=='a':
        print(w)

I have error: string index out of range

CodePudding user response:

With this condition added, your code should ignore strings shorter than 3 characters, which are the cause of the error you are getting.

for w in df['names_mother']:
    if len(w) >= 3 and w[2]=='a':
        print (w)

CodePudding user response:

You need to check that the word you are iterating over, and checking the third letter of, actually contains at least three letters:

for w in df['names_mother']:
    if len(w) >= 3:
        if w[2]=='a':
            print (w)

CodePudding user response:

Try checking if the name is longer than or equal to 3 characters as well:

import pandas as pd

df = pd.DataFrame(data={'names_mother': ['a', 'aaa', 'bbb', 'ccac']})
print(df)

for w in df['names_mother']:
    if len(w) >= 3 and w[2] == 'a':
        print(f'{w} has the letter \'a\' as its 3rd character')

Output:

  names_mother
0            a
1          aaa
2          bbb
3         ccac
aaa has the letter 'a' as its 3rd character
ccac has the letter 'a' as its 3rd character
  • Related