Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string without non-characters

Tags:

python

split

I'm trying to split a string that looks like this for example:

':foo [bar]'

Using str.split() on this of course returns [':foo','[bar]']

But how can I make it return just ['foo','bar'] containing only these characters?

like image 557
CosmicRabbitMediaInc Avatar asked Dec 16 '22 04:12

CosmicRabbitMediaInc


1 Answers

I don't like regular expressions, but do like Python, so I'd probably write this as

>>> s = ':foo [bar]'
>>> ''.join(c for c in s if c.isalnum() or c.isspace())
'foo bar'
>>> ''.join(c for c in s if c.isalnum() or c.isspace()).split()
['foo', 'bar']

The ''.join idiom is a little strange, I admit, but you can almost read the rest in English: "join every character for the characters in s if the character is alphanumeric or the character is whitespace, and then split that".

Alternatively, if you know that the symbols you want to remove will always be on the outside and the word will still be separated by spaces, and you know what they are, you might try something like

>>> s = ':foo [bar]'
>>> s.split()
[':foo', '[bar]']
>>> [word.strip(':[]') for word in s.split()]
['foo', 'bar']
like image 105
DSM Avatar answered Dec 27 '22 08:12

DSM