Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to include spaces with findall() function

Not experienced with regex so I’m having some trouble with findall(). More specifically I’m having trouble with making it so it includes whitespaces when it finds the ‘matches’ in a given string. Right now I have it where it finds the first letter that is immediately after a given character in a string.
For example, if I were given the string below and a pattern of ‘an’:

import re
s = "brand wham bam blank"
pattern = r'an(\w)'
characters_list = []
matches = re.findall(pattern,s)
for match in matches:
    characters_list.append(match[0].lower())
print(characters_list)

it would give a list:

['d', 'k']

but I’m having trouble with making it so it includes the first immediate whitespace (if it happens to be after the pattern given).
If the string above were to instead be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

s = "brand wham bam blank ban"

I would want the resulting list to be:

['d', 'k', ' ']

How could I go about doing this?

>Solution :

There is no space after an. Then why do you want a space in the list?
even if there is a space after an it can n0t include because \w is "any word character" which usually means alphanumeric (letters, numbers, regardless of case) plus underscore (_)[1]

If you want then try this with a string that has a space after an.

import re
s = "brand wham bam blank ban "
pattern = r'an(\w|\s)'
characters_list = []
matches = re.findall(pattern,s)
for match in matches:
    characters_list.append(match[0].lower())
print(characters_list)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading