Split string without characters

I am trying to break a line that looks like this:

':foo [bar]' 

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

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

+4
source share
4 answers

I do not like regular expressions, but I like Python, so I will 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 idiom ".join" is a bit strange, I admit, but you can almost read the rest in English: "append each character to the characters in s if the character is alphanumeric or the character is a space, then separate that."

Alternatively, if you know that the characters you want to delete will always be outside, and the word will still be separated by spaces, and you know what it is, you can try something like

 >>> s = ':foo [bar]' >>> s.split() [':foo', '[bar]'] >>> [word.strip(':[]') for word in s.split()] ['foo', 'bar'] 
+10
source

Make str.split() as usual, and then str.split() each element to remove non-letters. Sort of:

 >>> my_string = ':foo [bar]' >>> parts = [''.join(c for c in s if c.isalpha()) for s in my_string.split()] ['foo', 'bar'] 
+1
source

You will need to go through the list ['foo','[bar]'] and cross out all non-letter characters using regular expressions. Check Regex replace (in Python) - an easier way? for examples and documentation links.

0
source

You need to try regular expressions .

Use re.sub () to replace the characters :,[,] and split the resulting string into white space as a delimiter.

 >>> st = ':foo [bar]' >>> import re >>> new_st = re.sub(r'[\[\]:]','',st) >>> new_st.split(' ') ['foo', 'bar'] 
0
source

Source: https://habr.com/ru/post/1396000/


All Articles