lundi 23 novembre 2020

use a variable within a regular expression in python [duplicate]

I am trying to print a random word from a list starting with a letter from input I have tried this code. but I have to create list for every alphabet.

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))
letter = input("starting letter : ") #eg: a , b, c etc.
list = re.findall("[a]\w+", text) #list of words starting with 'a' from mylist
lrandom_word = random.choice(list)
print(lrandom_word)

How to add letter = input("starting letter : ") into list = re.findall("[a]\w+", text)

something like list = re.findall("[{letter}]\w+", text)

or any other way to print a random word from a list starting with an input letter.




Aucun commentaire:

Enregistrer un commentaire