What is the equivalent of PHP explode in Python?

Asked

Viewed 3,768 times

3

In PHP, if I want to split a string into several parts based on a delimiter, I use explode.

How can I do the same in Python?

2 answers

6


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

The split allows specifying 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, thus:

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

In this example the separation was made by ,.

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

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

Now only 2 divisions were made, leaving 3 elements.

It may also not indicate the separator, which will separate it by space, which is the most common case. This simplifies a lot in everyday life as 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 consult job documentation.

2

Using the very example of explode from the PHP documentation, 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.