How to include spaces with findall() function

Question:

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:

s = "brand wham bam blank ban"

I would want the resulting list to be:

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

How could I go about doing this?

Asked By: kyxgp

||

Answers:

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)

Answered By: codester_09
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.