john
john

Reputation: 31

Search for strings in a list with specific characters

I would like to create a piece of code that takes in a character and the position of that character in a word, then the code prints all the words from the wordlist with that letter in it but not in that position.

So for example if the list was [arm, bark, smack, smog ] And I said the character was A and It was in the first place the code will return bark and smack, and not arm as the A is the in the first place.

I have tried this so far

 wlist = ['arm','bark','smack','smog']
        letter13 = input('what was the letter: ')
        position13 = int(input('what was the position of the letter : '))
        filtered13 = [x for x in wlist if x != [position13 - 1] == letter13]
        print(filtered13)

Upvotes: 0

Views: 82

Answers (3)

TessellatingHeckler
TessellatingHeckler

Reputation: 28963

[x for x in wlist if x != [position13 - 1] == letter13]

You are heading in the right direction, but in this code wlist is a list of words, so x is a word like "arm". [position13 - 1] is a list with a number in it. letter13 is the letter 'a'. So this says:

'arm' is not equal to (a list with 1 in it being equal to the letter 'a').

That does not make sense for what you are asking. You need x[] to index into the word and pick out a letter, and you need two separate tests (letter in word at all) and (letter not in a specific position).

e.g.

def test(letter, index):
    wordlist = ["arm", "bark", "smack", "smog"]

    return [w for w in wordlist if (letter in w) and (w[index] != letter)]


>>> print(test('a', 1))
['arm', 'smack']

Upvotes: 0

KapJ1coH
KapJ1coH

Reputation: 138

bunch_of_words = ['arm', 'bark', 'smack', 'smog']
letter_index = 0
letter = 'a'

bunch_of_words = [word for word in bunch_of_words if letter in word and word[letter_index] != letter]

print(bunch_of_words)

Upvotes: 1

Nikolaj Š.
Nikolaj Š.

Reputation: 1986

def has_but_elsewhere(char, pos, wordlist):
    return [w for w in wordlist
            if len(w) >= pos and char in w and w[pos-1] != char]
>>> wordlist = ['arm', 'bark', 'smack', 'smog']
>>> print(has_but_elsewhere('a', 1, wordlist))
['bark', 'smack']

Upvotes: 0

Related Questions