Python Tokenization Strings

I am new to python and would like to know how I can tokenize strings based on the specified delimiter. For example, if I have the string "brother" and I would like to turn it to "brother", "\ s"] or the string "red / blue" to ["red", "blue"], which would be the most suitable way for this? Thank.

+3
source share
3 answers

You would use the split method :

>>> 'red/blue'.split('/')
['red', 'blue']
>>> "brother's".split("'")
['brother', 's']
+2
source

What you are looking for is called split, and it calls the object str. For instance:

>>> brotherstring = "brother's"
>>> brotherstring.split("'")
['brother', 's']
>>> redbluestring = "red/blue"
>>> redbluestring.split("/")
['red', 'blue']

split , rsplit, partition .., . , , .

+1

.

>>> strr =  "brother's"
>>> strr.replace("'","\\'").split("\\")
['brother', "'s"]

>>> strrr = "red/blue"
>>> strrr.split('/')
['red', 'blue']
+1

All Articles