How to Split a String in Python

  • google plus

In Brief...

In Python, you split a string into a list using the split() method.

Take our Introduction to Python Training course for free.

See the Course Outline and Register

Instructions

  1. Start with a string that has a delimiter on which you would like to split:
    s = 'apples,bananas,pears'
  2. Call split() on the string, passing it the delimiter:
    s.split(',')
  3. The result:
    ['apples', 'bananas', 'pears']

A couple things to note about the split() method:

  1. The default delimiter is a space:
    s = 'apples bananas pears'
    s.split()
    Result:
    ['apples', 'bananas', 'pears']
  2. It does not trim the results:
    s = 'apples, bananas, pears'
    s.split(',')
    Result:
    ['apples', ' bananas', ' pears']
    Notice the spaces at the beginning of '_bananas' and '_pears'.

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, XML, Windows, Java, Adobe, HTML5, JavaScript, Angular, and much more. Check out our complete course catalog.

Categories

Courses

Author: Nat Dunn

Nat Dunn founded Webucator in 2003 to combine his passion for technical training with his business expertise and to help companies benefit from both. His previous experience was in sales, business and technical training, and management. Nat has an MBA from Harvard Business School and a BA in International Relations from Pomona College.

Discuss