99 of 151 menu

The split method of the re module

The split method of the re module splits a string and returns the resulting list. The first parameter is a regular expression. The second parameter specifies the string we want to split. The third optional parameter specifies the maximum number of parts to split. The fourth optional parameter specifies flags for additional regular expression settings.

Syntax

import re re.split(regular expression, string, [max. number of parts], [flags bunting])

Example

Let's split the line at the hyphen:

txt = 'aaa-bbb-123 456' res = re.split('-', txt) print(res)

Result of code execution:

['aaa', 'bbb', '123 456']

Example

Now let's split the line at the hyphen twice:

txt = 'aaa-bbb-123-456' res = re.split('-', txt, 2) print(res)

As can be seen from the code execution result, the string was split at the hyphen only into two parts. And the third part of the string included its remainder:

['aaa', 'bbb', '123-456']

See also

  • method findall of module re,
    which returns a list of all matches in a string
  • method finditer of module re,
    which returns an iterator of all matches of the regular expression in the string
  • method search of module re,
    which looks for the first match of a regular expression in a string
  • method match of module re,
    which looks for a match with a regular expression at the beginning of a line
  • method fullmatch of module re,
    which looks for all matches of a regular expression in a string
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline