GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • The Python Code
  • Tutorials
  • Ethical Hacking
  • Machine Learning
  • General Python Tutorials
  • Web Scraping
  • Finance
  • Computer Vision
  • Python Standard Library
  • Application Programming Interfaces
  • Database
  • Game Development
  • Web Programming
  • Digital Forensics

This view

  • Original page
  • New address

GeezerVison is showing thepythoncode.com — How to Split a String In Python - The Python Code

Kickstart your coding journey with our Python Code Assistant. An AI-powered assistant that's always ready to help. Don't miss out!

Python is one of the best and most used languages among developers because of its easiness of learning and the extensive libraries that support the development of web applications and deep learning models, and the list is extended.

This article will help you learn one of the most straightforward commands in Python: splitting a string, which can be helpful in many programs. Like other programming languages, the string is a collection of characters that can be anything like a symbol and a number with a length of 1, and the character in this language doesn't have a data type. Keep in mind that everything in Python is an object, so the string is also treated as an object.

1. Splitting a String

Let's start by declaring a simple string, then try to split it and see the other parameters we can use with the split function.

#Declare Two Variables
variable1 = "Splitting a string"
variable2 = 'Splitting another string'

So we can use a double quotation or single quotation to declare a string without specifying the type of that variable, which will simplify the work with this language compared to others such as C++ or Java. Let's use the split function and deep dive into using it:

#Splitting The Variables
print(variable1.split())
print(variable2.split())

Output:

['Splitting', 'a', 'string']
['Splitting another string']

You can see the split() function splits the strings word by word, putting them in a Python list. It uses the spaces between the words to know how to separate them by default, but that can be changed. Let's see another example:

#Splitting The Variables
print(variable1.split())
print(variable2.split(","))

Output:

['Splitting', 'a', 'string']
['Splitting another string']

We've specified the type of separator we want to use for the second variable, which was "," the comma, and you will see that it will give you the whole word "Splitting another string" as one string because there is no comma between them to use as a separator. Let's try to use another example to understand more:

#Declare Two Variables
variable1 = "Splitting*a*string"
variable2 = 'Splitting,another,string'
#Splitting The Variables
print(variable1.split("*"))
print(variable2.split(","))

Output:

['Splitting', 'a', 'string']
['Splitting', 'another', 'string']

You see, we've changed the variables and separated the first variable with an asterisk "*" and the second one with a comma "," and you need to specify the separator in the split() function.

2. Accessing Strings

When you split the strings using the split() method, it will convert them directly to a list, and we can access them. Let's see an example:

#Splitting The Variables
print(variable1.split("*")[2])
print(variable2.split(",")[0])

Output:

string
Splitting

You can see by using square brackets and putting the index of that string. It starts counting from 0, meaning 0 is the first string in the array.

3. The maxsplit Parameter

You can add an optional parameter to the split() function called maxplit, which is the maximum number of splits to do. Let's see an example:

#Declare The Variable
variable = "Splitting a string"
#Use The Maxsplit
print(variable.split(" ", maxsplit=1))

Output:

['Splitting', 'a string']

Instead of splitting twice (as there are two spaces), the result is now only one split, the first split.

4. Splitting The String By Characters

We've seen how you can split the string by words, but you can also separate them by characters using a simple command. Let's see an example:

#Declare The Variable
variable = "Splitting a string"
#Split The String By Characters
print(list(variable))

Output:

['S', 'p', 'l', 'i', 't', 't', 'i', 'n', 'g', ' ', 'a', ' ',
's', 't', 'r', 'i', 'n', 'g']

We've used the list() function to split every character from the words, and every character is called a token or a chunk, and you can also access any character of them using the same previous method.

Conclusion

The split() function is a convenient built-in method for splitting a phrase into words or chunks using a delimiter which can be anything you want, from a space to an asterisk. Accessing the string is also easy to do with the Python language and is commonly used to work with text.

Learn also: How to Organize Files by Extension in Python.

Happy coding ♥

Just finished the article? Why not take your Python skills a notch higher with our Python Code Assistant? Check it out!

View Full Code Assist My Coding
Sharing is caring!

Read also

Logging in Python

Learn how to use Python's built-in logging module to log your Python applications, changing default format, level, and learning in a concrete example, as well as using logging handlers.

How to Handle Files in Python

Learn how to work with files in Python using os and shutil modules including creating, renaming, moving, removing files and directories, listing all current files and directories and more.

Daemon Threads in Python

Learn what daemon threads are with toy examples as well as real world examples and how to set daemon threads in Python

Comments

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!




    Get our free Python guides

    Join 50,000+ Python programmers and enthusiasts like you!

    Topics
    Ethical Hacking Machine Learning General Python Tutorials Web Scraping Finance Computer Vision Python Standard Library Application Programming Interfaces Database Game Development Web Programming Digital Forensics Natural Language Processing Healthcare PDF File Handling Python for Multimedia GUI Programming Cryptography Packet Manipulation Using Scapy
    New tutorials View all
    • How AI Text Detection Works: The Technology Behind Modern AI Detectors
    • Beyond Guesswork: How Python Helps Identify AI-Generated Text
    • Discover the Possibilities of Python Programming
    • How to Track Your AI Visibility with Python
    • How to Automate Excel Reports in Python using Openpyxl
    Popular tutorials View all
    • How to Convert Speech to Text in Python
    • How to Read Emails in Python
    • How to Extract Tables from PDF in Python
    • How to Control your Mouse in Python
    • How to Make a Keylogger in Python
    Ethical Hacking with Python EBook - Topic - Bottom CodingFleet - Topic - Bottom
    You are visitor 01402503 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.