ducttape101
ducttape101

Reputation: 51

How to use re.findall to find all characters in a string, including special characters?

If I have a list like this:

names = ['S. Planet', 'A. Planet-World', 'Dog World', 'Dog-Cat Planet']

I want to generate a new list with the last words from the list, including all special characters, like this:

new_names = [['S.', 'Planet'], ['A.', 'Planet-World'], ['Dog', 'World'], ['Dog-Cat', 'Planet']]

My code looks like this, but I can't figure out how to look at the special characters. How would I fix this small thing? I'm new to Python and still learning.

new_names = [(re.findall(r"([a-zA-Z]+)", x)) for x in names]
print(new_names)
#[['S', 'Planet'], ['A', 'Planet', 'World'], ['Dog', 'World'], ['Dog', 'Cat', 'Planet']]

I would appreciate any help. Thank you!

Upvotes: 0

Views: 216

Answers (2)

Kawish Qayyum
Kawish Qayyum

Reputation: 181

You simply use the str.split() method like this:

new_names = [name.split() for name in names]

Output:

[
    ['S.', 'Planet'],
    ['A.', 'Planet-World'],
    ['Dog', 'World'],
    ['Dog-Cat', 'Planet']
]

Upvotes: 3

I would do this differently. It seems to me that all you're doing is splitting by space, so it makes sense to just look at that and not try to figure out how to handle the special characters.

names = ['S. Planet', 'A. Planet-World', 'Dog World', 'Dog-Cat Planet']
new_names = map(str.split, names)

Since I'm not sure how common it is to use map/functional programming, I'll explain what it does. Map has the same effect as iterating through a list and then applying a function (the str.split function, in this case) to each element. The result of this is then returned as a new object that can be cast to a list.

Upvotes: 3

Related Questions