-1

I'm studying the string in Python and I want to split a string using multiple separators. For this reason I saw the re.split() method, but I don't understand the parameter called "pattern".

  • 4
    I assume you've looked at http://docs.python.org/2/library/re.html#re.split? The pattern is a regular expression defining the characters you want to split on. – Christian Ternus Oct 16 '13 at 19:12
  • possible duplicate of [Python strings split with multiple separators](http://stackoverflow.com/questions/1059559/python-strings-split-with-multiple-separators) – Christian Ternus Oct 16 '13 at 19:13
  • Yes I did, but in this case for example:re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE). What is "[a-f]+"? – Alessio Vinaccia Oct 16 '13 at 19:17
  • @AlessioVinaccia `[a-f]` means *all letters from a to f* and `+` means *at least one*. It's a regular expression. So anything matched by that pattern will be treated as a separator. In your case `a` and `B` matches it (because of `IGNORECASE`, normally it is case sensitive) thus it will produce `['0','3','9']`. – freakish Oct 16 '13 at 19:17

2 Answers2

0

pattern is the Regular Expression you want to base the splits off of. See below:

>>> import re
>>> help(re.split)
Help on function split in module re:

split(pattern, string, maxsplit=0, flags=0)
    Split the source string by the occurrences of the pattern,
    returning a list containing the resulting substrings.

>>>

Here is a good reference on Regular Expressions.

0
>>> s='thing 1,obj 2;name 3:you get the picture'
>>> re.split(r',|;|:',s)
['thing 1', 'obj 2', 'name 3', 'you get the picture']
dawg
  • 98,345
  • 23
  • 131
  • 206
  • Hi,in this case what 'r' represents in split method? – Alessio Vinaccia Oct 16 '13 at 19:40
  • @AlessioVinaccia - The `r` makes the string a raw string, which doesn't process escape sequences. Those are handy with regular expressions (note however that it is not _needed_ here). –  Oct 16 '13 at 19:45
  • The `r` means 'raw'. It is commonly used with regex patterns. It is a different way of describing a string literal. – dawg Oct 16 '13 at 19:45
  • @iCodez: Not *needed* but *habit*! ;-) – dawg Oct 16 '13 at 19:46