What is the equivalent of 'explode' from PHP in Python?

2

In PHP, if I want to split a multi-part string based on a delimiter, I use explode .

How can I do the same in Python?

    
asked by anonymous 15.06.2018 / 05:33

2 answers

5

split is the equivalent of explode of PHP, which is a string method. In fact almost all languages in which this functionality exists is called split , with PHP being the only (or almost) giving it a different name (for its reasons I know).

The split allows you to specify two parameters:

  • sep - separator
  • maxsplit - maximum of divisions to be made

Something like:

str.split(separador, divisoes)

The normal is not to indicate the number of divisions and only the separator, like this:

>>> str = 'um,dois,tres,quatro,cinco'
>>> str.split(',')
['um', 'dois', 'tres', 'quatro', 'cinco']

In this example the separation was done by , .

When it indicates maxsplit , it only divides as many times as the indicated number:

>>> str = 'um,dois,tres,quatro,cinco'
>>> str.split(',', 2)
['um', 'dois', 'tres,quatro,cinco']

Now only 2 divisions have been made, thus leaving 3 elements.

It also may not indicate the separator, which will separate you by space, which is the most common case. This simplifies a lot on a daily basis since it is the most normal to use as a separator:

>>> str = 'um dois tres quatro cinco'
>>> str.split()
['um', 'dois', 'tres', 'quatro', 'cinco']

Whenever you have questions, you should refer to function documentation .

    
15.06.2018 / 15:30
2

By using the explode example of the PHP documentation itself, you simply need to do

pizza  = "piece1 piece2 piece3 piece4 piece5 piece6"
pizza.split(' ')
['piece1', 'piece2', 'piece3', 'piece4', 'piece5', 'piece6']

No need to import string.

    
15.06.2018 / 13:55