Python String split() - GeeksforGeeks (2024)

Python String split() method splits a string into a list of strings after breaking the given string by the specified separator.

Example:

Python
string = "one,two,three"words = string.split(',')print(words)

Output:

['one', 'two', 'three']

Python String split() Method Syntax

Syntax: str.split(separator, maxsplit)

Parameters

  • separator: This is a delimiter. The string splits at this specified separator. If is not provided then any white space is a separator.
  • maxsplit: It is a number, that tells us to split the string into a maximum of the provided number of times. If it is not provided then the default is -1 which means there is no limit.

Returns

Returns a list of strings after breaking the given string by the specified separator.

What is the list split() Method?

split() function operates on Python strings, by splitting a string into a list of strings. It is a built-in function in Python programming language.

It breaks the string by a given separator. Whitespace is the default separator if any separator is not given.

How to use list split() method in Python?

Using the list split() method is very easy, just call the split() function with a string object and pass the separator as a parameter. Here we are using the Python String split() function to split different Strings into a list, separated by different characters in each case.

Example: In the above code, we have defined the variable ‘text’ with the string ‘geeks for geeks’ then we called the split() method for ‘text’ with no parameters which split the string with each occurrence of whitespace.

Python
text = 'geeks for geeks'# Splits at spaceprint(text.split())word = 'geeks, for, geeks'# Splits at ','print(word.split(','))word = 'geeks:for:geeks'# Splitting at ':'print(word.split(':'))word = 'CatBatSatFatOr'# Splitting at tprint(word.split('t'))

Similarly, after that, we applied split() method on different strings with different delimiters as parameters based on which strings are split as seen in the output.

Output

['geeks', 'for', 'geeks']['geeks', ' for', ' geeks']['geeks', 'for', 'geeks']['Ca', 'Ba', 'Sa', 'Fa', 'Or']

Time Complexity: O(n)
Auxiliary Space: O(n)

How does split() work when maxsplit is specified?

The maxsplit parameter is used to control how many splits to return after the string is parsed. Even if there are multiple splits possible, it’ll only do maximum that number of splits as defined by the maxsplit parameter.

Example: In the above code, we used the split() method with different values of maxsplit. We give maxsplit value as 0 which means no splitting will occur.

Python
word = 'geeks, for, geeks, pawan'# maxsplit: 0print(word.split(', ', 0))# maxsplit: 4print(word.split(', ', 4))# maxsplit: 1print(word.split(', ', 1))

The value of maxsplit 4 means the string is split at each occurrence of the delimiter, up to a maximum of 4 splits. And last maxsplit 1 means the string is split only at the first occurrence of the delimiter and the resulting lists have 1, 4, and 2 elements respectively.

Output

['geeks, for, geeks, pawan']['geeks', 'for', 'geeks', 'pawan']['geeks', 'for, geeks, pawan']

Time Complexity: O(n)
Auxiliary Space: O(n)

How to Parse a String in Python using the split() Method?

In Python, parsing strings is a common task when working with text data. String parsing involves splitting a string into smaller segments based on a specific delimiter or pattern. This can be easily done by using a split() method in Python.

Python
text = "Hello geek, Welcome to GeeksforGeeks."result = text.split()print(result)

Explanation: In the above code, we have defined a string ‘text’ that contains a sentence. By calling the split() method without providing a separator, the string is split into a list of substrings, with each word becoming an element of the list.

Output

['Hello', 'geek,', 'Welcome', 'to', 'GeeksforGeeks.']

Hope this tutorial on the string split() method helped you understand the concept of string splitting. split() method in Python has various applications like string parsing, string extraction, and many more. “How to split in Python?” is a very important question for Python job interviews and with this tutorial we have answered the question for you.

Check More: String Methods

For more informative content related to the Python string split() method you can check the following article:

  • Python program to split and join a string
  • Split and Parse a string in Python
  • Python | Ways to split a string in different ways
  • Python | Split string into list of characters

Python String split() – FAQs

What does split('\t') do in Python?

In Python, the split('\t') method splits a string into a list of substrings based on the tab (\t) delimiter. Here’s how it works:

text = "apple\tbanana\torange"
result = text.split('\t')
print(result) # Output: ['apple', 'banana', 'orange']

In this example, the split('\t') method divides the string text wherever it encounters a tab character (\t) and returns a list containing the separated substrings.

What is input().split() in Python?

input() is a built-in function in Python that reads a line from input, which is typically from the user via the console. split() is a method that splits a string into a list of substrings based on whitespace by default, or a specified delimiter. Together, input().split() allows you to read user input and split it into individual components based on whitespace.

Example:

# User input: "apple banana orange"
words = input().split()
print(words) # Output: ['apple', 'banana', 'orange']

Here, input() reads the input from the user, and split() divides the input into a list of words based on whitespace.

How to split a number in Python?

To split a number (typically an integer or float) into its individual digits, you can convert the number to a string and then split the string. Here’s an example:

number = 12345
digits = list(str(number))
print(digits) # Output: ['1', '2', '3', '4', '5']

In this example, str(number) converts the integer 12345 into a string, and list() converts the string into a list of individual characters (‘1’, ‘2’, ‘3’, ‘4’, ‘5’).

How to split a string into lines using the split() method?

To split a multi-line string into individual lines using the split() method, you can specify the newline character (\n) as the delimiter. Here’s an example:

multiline_text = "Line 1\nLine 2\nLine 3"
lines = multiline_text.split('\n')
print(lines) # Output: ['Line 1', 'Line 2', 'Line 3']

In this example, split('\n') splits the multiline_text string wherever it encounters a newline character (\n) and returns a list of lines.

How to split a string number?

If by “split a string number” you mean splitting a string representation of a number into its individual characters or parts, you can use the split() method with an empty string as the delimiter. Here’s an example:

number_str = "12345"
digits = list(number_str)
print(digits) # Output: ['1', '2', '3', '4', '5']

In this example, list(number_str) converts the string "12345" into a list of individual characters (‘1’, ‘2’, ‘3’, ‘4’, ‘5’).



pawan_asipu

Python String split() - GeeksforGeeks (2)

Improve

Next Article

Python String rsplit() Method

Please Login to comment...

Python String split() - GeeksforGeeks (2024)

FAQs

Python String split() - GeeksforGeeks? ›

split() function operates on Python strings, by splitting a string into a list of strings. It is a built-in function in Python programming language. It breaks the string by a given separator. Whitespace is the default separator if any separator is not given.

What does split() do in Python? ›

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.

How do you split a string into substrings in Python? ›

Whenever there is a need to break bigger strings or a line into several small strings, you need to use the split() function in Python. The split() function still works if the separator is not specified by considering white spaces, as the separator to separate the given string or given line.

How to split string between two characters in Python? ›

The split() method is the most common way to split a string into a list in Python. This method splits a string into substrings based on a delimiter and returns a list of these substrings. In this example, we split the string "Hello world" into a list of two elements, "Hello" and "world" , using the split() method.

How do you split a string and get the first element in Python? ›

To extract the first word, we can use the str. split() method, which splits a string into a list of words. We can then access the first element of the list using indexing ( [0] ).

What is the difference between split () and slicing in Python? ›

In essence: - `split()` divides a string into smaller parts based on a character or pattern. - Slicing extracts a portion of a string directly by specifying the start and end positions.

What does a split() function do with a string when applied to it? ›

The Split function breaks a text string into a table of substrings. Use Split to break up comma delimited lists, dates that use a slash between date parts, and in other situations where a well defined delimiter is used. A separator string is used to break the text string apart.

How do you split a string with a substring? ›

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.

How do you split a string into two lines in Python? ›

To split a long string over multiple lines in Python, you can use the line continuation character, which is a backslash ( \ ) at the end of the line. The string will continue on the next line as if it were a single line.

How do you cut a substring from a string in Python? ›

3 Methods to Trim a String in Python
  1. strip() : Removes leading and trailing characters (whitespace by default).
  2. lstrip() : Removes leading characters (whitespace by default) from the left side of the string.
  3. rstrip() : Removes trailing characters (whitespace by default) from the right side of the string.

How do you split a string in two places in Python? ›

In Python, we can split multiple characters from a string using replace(). This is a very rookie way of doing the split. It does not make use of regex and is inefficient but still worth a try. If you know the characters you want to split upon, just replace them with a space and then use split().

What is the regular expression to split a string in Python? ›

The . split() method of the re module divides a string into substrings at each occurrence of the specified character(s). This method is a good alternative to the default . split() string method for instances that require matching multiple characters.

How do you split a string by a specific character in Python? ›

Splitting on a Specific Substring

split('x') can be used to split a string on a specific substring 'x'. Without 'x' specified, . split() simply splits on all whitespace, as seen above.

How do you split a string into two parts in Python? ›

This can be easily done by using a split() method in Python. Explanation: In the above code, we have defined a string 'text' that contains a sentence. By calling the split() method without providing a separator, the string is split into a list of substrings, with each word becoming an element of the list.

How do you randomly split a string in Python? ›

Python split will split the corresponding string at every single space if no parameter is specified. The separator parameter specifies which string to split. The corresponding split will then take place where you have specified that it should occur. The maxsplit specifies how often the string should be split.

How do you split a string by new in Python? ›

The split() function can be used to split multiline strings into a list of lines. By using the newline character (“\n”) as the delimiter, the split() function divides the string into separate lines. In this example, the string text contains three lines separated by newline characters.

What does * input () split () mean in Python? ›

input() returns a string typed in at the command line. . split() , applied to a string, returns a list consisting of whitespace-free substrings that had been separated by whitespace.

What arguments does split take? ›

split() method accepts two arguments. The first optional argument is separator , which specifies what kind of separator to use for splitting the string. If this argument is not provided, the default value is any whitespace, meaning the string will split whenever . split() encounters any whitespace.

What is the function to split data in Python? ›

The split() method splits a string into a list in Python, given a specified delimiter. The method returns the substrings according to the number of delimiters in the given string.

What is the difference between partition () and split () methods in Python strings? ›

If you need to split a string into all possible substrings, split() is the way to go. However, if you're interested in only the first occurrence of the separator and want to keep the separator as part of the result, then partition() is more appropriate.

Top Articles
Top Careers Earning Over $200K Annually - Explore the elite careers that offer annual earnings of over $200,000, including qualifications and industry insights. - SQLPad.io
Hyper Scalper — A 80% Success Rate Crypto Trading Strategy [Extensive Post With Backtest Resultx]
What is Mercantilism?
What Are the Best Cal State Schools? | BestColleges
Toyota Campers For Sale Craigslist
Fnv Turbo
Bhad Bhabie Shares Footage Of Her Child's Father Beating Her Up, Wants Him To 'Get Help'
2021 Tesla Model 3 Standard Range Pl electric for sale - Portland, OR - craigslist
Ktbs Payroll Login
104 Presidential Ct Lafayette La 70503
Https //Advanceautoparts.4Myrebate.com
1Win - инновационное онлайн-казино и букмекерская контора
I Touch and Day Spa II
Extra Virgin Coconut Oil Walmart
Sam's Club La Habra Gas Prices
China’s UberEats - Meituan Dianping, Abandons Bike Sharing And Ride Hailing - Digital Crew
라이키 유출
Allentown Craigslist Heavy Equipment
Catherine Christiane Cruz
Sussur Bloom locations and uses in Baldur's Gate 3
Samantha Aufderheide
Ups Print Store Near Me
Maxpreps Field Hockey
Walmart Near South Lake Tahoe Ca
The Old Way Showtimes Near Regency Theatres Granada Hills
R&S Auto Lockridge Iowa
Wkow Weather Radar
T Mobile Rival Crossword Clue
Turbo Tenant Renter Login
Hefkervelt Blog
Saxies Lake Worth
Busted Mugshots Paducah Ky
Garden Grove Classlink
The Collective - Upscale Downtown Milwaukee Hair Salon
Eegees Gift Card Balance
3473372961
Newsday Brains Only
Vanessa West Tripod Jeffrey Dahmer
Andhra Jyothi Telugu News Paper
Mistress Elizabeth Nyc
Are you ready for some football? Zag Alum Justin Lange Forges Career in NFL
The Vélodrome d'Hiver (Vél d'Hiv) Roundup
Kelley Blue Book Recalls
Bill Manser Net Worth
Kutty Movie Net
6576771660
Quick Base Dcps
All Weapon Perks and Status Effects - Conan Exiles | Game...
The Great Brian Last
From Grindr to Scruff: The best dating apps for gay, bi, and queer men in 2024
Ajpw Sugar Glider Worth
Guidance | GreenStar™ 3 2630 Display
Latest Posts
Article information

Author: Corie Satterfield

Last Updated:

Views: 6252

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Corie Satterfield

Birthday: 1992-08-19

Address: 850 Benjamin Bridge, Dickinsonchester, CO 68572-0542

Phone: +26813599986666

Job: Sales Manager

Hobby: Table tennis, Soapmaking, Flower arranging, amateur radio, Rock climbing, scrapbook, Horseback riding

Introduction: My name is Corie Satterfield, I am a fancy, perfect, spotless, quaint, fantastic, funny, lucky person who loves writing and wants to share my knowledge and understanding with you.