Reputation: 37
I am trying to find a specific character in a list of words and then print all the words that match. for example, I have a list of 6 words. I would like to find a way to select all the words with a ('.') (fullstop) in them and transfer them to another list.
Example:
List ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
I would like it to find Charlie and its position in the list
I mostly just need the if statement for it Thanks in advance!
This is what I have so far
sent = str(input('enter sentance '))
words = sent.split()
print (words)
Upvotes: 1
Views: 1580
Reputation: 175
The usual way to know if a character is in a string in python is "in"
'.' in "charlie."
that will return True.
To know the position of an element in a list you can iterate using enumerate(list) and will return a pair of (index,value).
To get a list of the index and the strings who have '.' character you can do something like this:
[(pos, word) for pos, word in enumerate(list) if '.' in word]
Upvotes: 1
Reputation: 3859
Assume you have a list l = ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
Then you can create a list with all words containing '.' in it by doing filter like below:
l = ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
list_with_dot = [x for x in l if x.find('.') != -1]
Upvotes: 3
Reputation: 3245
If you want it without list comprehension:
sent = input('Enter sentence > ')
words = sent.split()
for word in words:
if "." in word:
print(word)
Also, you if you're in Python 2.7, use raw_input
, input
for Python 3.
Upvotes: 1
Reputation: 16214
you can try this (for python 2.7)
sent = raw_input('enter sentance ')
lista = ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
res = [i for i in lista if (sent in i)][0]
print(str(res) + "is at index " + str(lista.index(res)))
Upvotes: 1