lundi 23 novembre 2020

How to get words STARTING with a letter in python using regular expression [duplicate]

I am trying to print a random word from a list starting with a letter. import random import re

#print random word from mylist
mylist = ["apple","ant","air","ball","boat" ,"banana","car" ,"car","cherry"]
random_word = random.choice(mylist)
print(random_word)

#print random word starting with 'a' from mylist
text = ' '.join(map(str, mylist))

list = re.findall("[a]\w+", text) #list of words starting with 'a' from mylist
lrandom_word = random.choice(list)
print(lrandom_word)

but it shows invalid words also

output ['apple', 'ant', 'air', 'all', 'at', 'anana', 'at', 'ar']

output should be ['apple', 'ant', 'air']

How to get valid words from this string.




Aucun commentaire:

Enregistrer un commentaire