How to Split Strings in Python With the split() Method

Real Python · Beginner ·🛠️ AI Tools & Apps ·7y ago

Key Takeaways

The video demonstrates the usage of the split() method in Python for splitting strings into substrings based on a separator character or string, with examples of default behavior, custom separators, and the maxsplit parameter.

Full Transcript

hello everyone welcome to our second video in the series on splitting concatenating and joining strings in Python this video will focus on the string methods split split creates a list of sub strings from the string instance that invoked it before we get started let's review two things from the previous video first strings are immutable sequences meaning they can't be changed this property is key to understanding string methods in general string methods can't modify the string instance they're invoked upon therefore the string methods we discuss here we'll all be creating new values or objects second although string methods can be invoked as static methods directly from the string class this is not recommended going forward we will explore our string methods by invoking them the usual way from their string object instance now let's talk about split here we see an example of the split method the job of split is to create sub strings based on the position of a separator character or string within the string instance split then returns a list object with those sub strings as elements the separator used to delimit these string portions depends on what if any character or string was passed as an argument since this argument is used in this way only strings can be passed as the separator there are no restrictions however on the type of character or length of string that serves this purpose the split method can be invoked without passing any arguments if nothing is passed split uses whitespace as its default separator as you can see invoking split from our sentence string effectively creates a list of words with this default behavior split can be helpful in generating a word count on large blocks of text once a split is called on the text block Len can be used to count the elements in the returned list sometimes however we don't want split to use white space as our string delimiter for example say we wanted to break apart our sentence string at the lowercase s we simply pass the lowercase s as a string argument to split split we'll then use that character as a separator to generate the list elements which you can see from this result note also that the separator character the S is missing from the sub strings that were generated so how could this be useful you may have seen data in a format known as CSV or comma separated values here's an example of the United States zip code data in this format split can be useful in reading CSV data because we can specify the comma character as our split delimiter thereby identifying the field values within each record or row since split uses white space as its default separator you might assume that explicitly passing a space character string argument would function the same but there is a slight difference this difference is apparent in the returned list when working upon a stream with leading or trailing whitespace in this situation passing a literal space character to split produces empty strings in the list result another useful feature of split involves the use of its optional second parameter max split the default value of back split is negative 1 which means it has no real effect however if a positive integer has passed us the max split argument that number will be the maximum number of times a split will use the separator for example if a 1 is specified from xsplit the split methods job is complete after the first separator position is found the remaining separators will then be ignored so how might max split be useful if we revisit our zip code CSV example let's suppose we want to treat the city and state as one field value called location without specifying the max split argument a split on the comma character would render a three string list however specifying the integer one for max split would stop splitting after the first comma the one following the zip code now split returns a two string list where we can treat our city and state as one field here you see the comma after the city is now part of the string in the second element hopefully this video showed how split can be useful and perhaps you can use split in some of your own applications now that we've broken our strings of parts let's put them back together again in the next video

Original Description

Download your free Python Cheat Sheet here: https://realpython.com/cheatsheet Free Python Skill Test with instant level + learning plan: https://realpython.com/skill-test Want to learn faster? Become a Python Expert with unlimited access to 5,000+ tutorials, videos, and exercises: https://realpython.com/start You'll learn how to split strings in Python using the .split() method. .split() has optional parameters that allow you to fine tune how strings are split. You’ll see how to use a bare call to .split() to cut out whitespace from a string and get a list of words. You’ll also learn how to specify separators and also limit the number of splits in calls to split() using the "maxsplit" parameter. Click here to learn more: https://realpython.com/courses/splitting-concatenating-and-joining-strings-python/ 🐍 Become a Python expert with real-world tutorials, on-demand courses, interactive quizzes, and 24/7 access to a community of experts at https://realpython.com ▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰ 🐍 Start Here → https://realpython.com/start 🗺️ Guided Learning Paths → https://realpython.com/learning-paths 🎧 Real Python Podcast → https://realpython.com/podcast 📚 Python Books → https://realpython.com/books 📖 Python Reference → https://realpython.com/ref 🧑‍💻 Quizzes & Exercises → https://realpython.com/quizzes 🎓 Live Courses: https://realpython.com/live ⭐️ Reviews & Learner Stories: https://realpython.com/learner-stories ▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 0 of 60

← Previous Next →
1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

The split() method in Python is used to split strings into substrings based on a separator character or string. This video demonstrates its usage with examples, including default behavior, custom separators, and the maxsplit parameter.

Key Takeaways
  1. Invoke the split() method on a string instance
  2. Pass a custom separator as an argument to split()
  3. Use the maxsplit parameter to limit the number of splits
  4. Apply split() to CSV data to parse field values
💡 The split() method returns a list of substrings and can be used with custom separators and the maxsplit parameter to parse data in various formats.

Related AI Lessons

Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →