Reputation: 63
I have a list and I want to compare user input with that list , but character by character. for example user can only input some character and leave the rest by dots. (for example : V...r..n ) How do I can compare strings character by character, and if it only includes all characters by user input (skip the dots)
list1 = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]
s = input() # for example "V...r..n"
for i in list1:
# if s include exactly characters in i (skip the dots)
print(i)
Upvotes: 0
Views: 111
Reputation: 164623
Here's one way. There are two steps. First make a dictionary mapping indices to relevant characters. Then check for equality for those indices.
L = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]
s = input()
d = {k: v for k, v in enumerate(s) if v != '.'}
for item in L:
if (len(s) == len(item)) and all(item[k] == v for k, v in d.items()):
print(item)
# V...r..n
# Vaporeon
Upvotes: 1
Reputation: 222802
You can use regular expressions:
import re
list1 = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]
s = input() # for example "V...r..n"
re_s = re.compile(''.join('.' if ch == '.' else re.escape(ch) for ch in s) + '$')
for i in list1:
if re_s.match(i):
print(i)
EDIT: Another option that seems missing from the other answers is to use itertools.zip_longest
:
from itertools import zip_longest
list1 = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]
s = input() # for example "V...r..n"
for i in list1:
if all(c1 == c2 for c1, c2 in zip_longest(i, s) if c2 != '.'):
print(i)
Upvotes: 2
Reputation: 176
There are some hard looking solutions here. I found this to be the easiest and working solution.
list1 = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]
s = input() # for example "V...r..n"
matchedList = []
for i in list1:
inputInList = True
for letter in s:
if not letter in i:
inputInList = False
break
if inputInList:
matchedList.append(i)
print(matchedList)
Upvotes: -1
Reputation: 3720
There are several ways to solve it, with regex, with the solution of jpp, or with this one:
list1 = ["Vaporeon", "Jolteon", "Flareon", "Espeon", "Umbreon", "Leafeon", "Glaceon", "Sylveon"]
s = input() # for example "V...r..n"
for word in list1:
l = len(word)
c = 0
flag = True
while c < l and flag:
if s[c] != '.':
if s[c] != word[c]:
flag = False
c += 1
if flag:
print(word)
Upvotes: 0