Home > Enterprise >  python: re.sub('[^A-Za-z]', ' ', string) for a list
python: re.sub('[^A-Za-z]', ' ', string) for a list

Time:04-15

Assume I have a list of strings such as

list1 = [['Hey There'],['Good Afternoon'],['How is your day']]

how can I use this code

re.sub('[^A-Za-z]', ' ', string).lower()

to go through all the strings at once instead of doing each individually. Can I do a loop?

at the end, end up with something like

list1 = [['hey there'],['good afternoon'],['how is your day']]

CodePudding user response:

You need to do it individually, one way or the other, because re.sub expects string to be a str or bytes.

Assuming each nested list only has 1 string:

import re

nested_list_of_string = [['Hey There'], ['Good Afternoon'], ['How Is Your Day']]

def lower_string_in_nested_list(list_):
    function = lambda list_: re.sub('[^A-Za-z]', ' ', list_[0]).lower()
    return [*map(function, list_)]

print(lower_string_in_nested_list(nested_list_of_string))

Output:

['hey there', 'good afternoon', 'how is your day']

map applies a function to every item in list_. In this case, the function just grabs the first (and only) item from list_, which is the string you want to lower, and calls re.sub.

CodePudding user response:

With a list comprehension:

list1 = [[re.sub('[^A-Za-z]', ' ', string).lower()]
         for string, in list1]

Try it online!

  • Related