Home > Uncategorized > Python: string.split() vs re.split()

Python: string.split() vs re.split()

While both string and regular expression in python has split() method, string.split() can split using only one separator.

def split_with_string():
    s = "how-r-you."
    assert s.split("-") == ['how', 'r', 'you.'] #True

On the other re.split() can split using regular expression. When you are using, you can build any complex separator or combine multiple separators.

def split_with_re():
    import re
    s = "how-r-you."
    assert re.split(r'[-|.]') == ['how', 'r', 'you', ''] #True

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: