什么是Python?什么是“爆炸”?

问题:什么是Python?什么是“爆炸”?

我有一个存储在变量中的字符串myvar = "Rajasekar SP"。我想像explode在PHP中那样使用定界符将其拆分。

Python中的等效项是什么?

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?


回答 0

选择您需要的一个:

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

str.splitstr.partition

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


回答 1

php中explode的替代方法是split

第一个参数是定界符,第二个参数是最大分割数。返回的部分不包含定界符(可能最后一个部分除外)。当定界符为“无”时,将匹配所有空格。这是默认值。

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

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

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']