What is for Python what 'explode' is for PHP?


Php Problem Overview

I had a string which is stored in a variable myvar = "Rajasekar SP". I want to split it with delimiter like we do using explode in PHP.

What is the equivalent in Python?

Php Solutions

Solution 1 - Php

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

Solution 2 - Php

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajasekarView Question on Stackoverflow
Solution 1 - PhpSilentGhostView Answer on Stackoverflow
Solution 2 - PhpPeter SmitView Answer on Stackoverflow