Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 24361

Python Morsels: The string split method in Python

$
0
0

Strings can be split by a substring separator. Usually the string split is called without any arguments, which splits on any whitespace.

Breaking apart a string by a separator

If you need to break a string into smaller strings based on a separator, you can use the string split method:

>>> time="1:19:48">>> time.split(":")['1', '19', '48']

The separator you split by can be any string. It doesn't need to be just one character:

>>> graph="A->B->C->D">>> graph.split("->")['A', 'B', 'C', 'D']

Note that it's a little bit unusual to call the string split method on a single space character:

>>> langston="Does it dry up\nlike a raisin in the sun?\n">>> langston.split("")['Does', 'it', 'dry', 'up\nlike', 'a', 'raisin', 'in', 'the', 'sun?\n']

It's usually preferable to call split without any arguments at all:

>>> langston="Does it dry up\nlike a raisin in the sun?\n">>> langston.split()['Does', 'it', 'dry', 'up', 'like', 'a', 'raisin', 'in', 'the', 'sun?']

Calling the split with no arguments will split on any consecutive whitespace characters. So we're even splitting on a new line here in between up and like (up\nlike).

Also note that the split method without any arguments removes leading and trailing whitespace (note that the last element in the list is sun? rather than sun?\n).

There's one more split feature that's often overlooked: maxsplit.

Splitting a specific number of times

When calling split with a …

Read the full article: https://www.pythonmorsels.com/string-split-method/


Viewing all articles
Browse latest Browse all 24361

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>