![]() |
|
[Tut] Python | Split String by Whitespace - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python | Split String by Whitespace (/thread-100143.html) |
[Tut] Python | Split String by Whitespace - xSicKxBot - 10-26-2022 Python | Split String by Whitespace Rate this post Summary: Use Code: "given string".split()Minimal Example: Code: print("Welcome Finxter".split())[b]Problem Formulation[/b] Problem: Given a string, How will you split the string into a list of words using whitespace as a separator/delimiter? Let’s understand the problem with the help of a few examples: Example 1: Input: text = “Welcome to the world of Python” Explanation: Split the string into a list of words using a space ” ” as the delimiter to separate the words from the given string. Output: [‘Welcome’, ‘to’, ‘the’, ‘world’, ‘of’, ‘Python’] Example 2: Input: text = “””Item_1 Item_2 Item_3″”” print(text.split(‘\n’)) Explanation: Split the string into a list of words using a newline “\n” as the delimiter to separate the words from the given string. Output: [‘Item_1’, ‘Item_2’, ‘Item_3’] Example 3: text = “This is just a random text:\n New Line” Explanation: The given string contains a combination of whitespaces between the words, such as space, multiple-spaces, a tab and a new line character. All of these whitespace characters have to be considered as delimiters while separating the words from the given string and storing them as items in a list. Here’s how the output looks: Output: [‘This’, ‘is’, ‘just’, ‘a’, ‘random’, ‘text:’, ‘New’, ‘Line’] So, we have two situations at hand. One, that has a single whitespace used as a delimiter and another that has multiple whitespace characters as delimiters in the same string. Let’s dive into the numerous ways of solving this problem. [b]Method 1: Using split()[/b] Code: split()Code: splitCode: finxterx42'.split('x')Code: ['fin', 'ter', '42']Read more about the Code: split()Approach: Thus to split a string based on a given whitespace delimiter, you can simply pass the specific whitespace character as a separator/delimiter to the Code: split('whitespace_character')Code: Code: # Example 1:
text = "Welcome to the world of Python"
print(text.split(' '))
# OUTPUT: ['Welcome', 'to', 'the', 'world', 'of', 'Python'] # Example 2:
text = """Item 1
Item 2
Item 3"""
print(text.split('\n'))
# OUTPUT: ['Item_1', 'Item_2', 'Item_3'] # Example 3: text = "This is just a\trandom text:\nNew Line"
print(text.split()) # OUTPUT: ['This', 'is', 'just', 'a', 'random', 'text:', 'New', 'Line']Note that to separate the words in the third example we did specify any separator within the Code: split()[b]Method 2: Using regex[/b] Another extremely handy way of separating a string with whitespace characters as separators is to use the regex library. Approach 1: Import the regex library and use its split method as Code: re.split('\s+', text)Code: Code: import re
# Example 1:
text = "Welcome to the world of Python"
print(re.split('\s+', text))
# OUTPUT: ['Welcome', 'to', 'the', 'world', 'of', 'Python'] # Example 2:
text = """Item_1
Item_2
Item_3"""
print(re.split('\s+', text))
# OUTPUT: ['Item_1', 'Item_2', 'Item_3'] # Example 3:
text = "This is just a\trandom text:\nNew Line"
print(re.split('\s+', text))
# OUTPUT: ['This', 'is', 'just', 'a', 'random', 'text:', 'New', 'Line']Related Tutorial: Python Regex Split Approach 2: Another way of using the regex library to solve this question is to use the Code: findall()Code: re.findall(r'\S+', text)Here’s a graphical representation of the above explanaton: ![]() Code: Code: import re
# Example 1:
text = "Welcome to the world of Python"
print(re.findall(r'\S+', text))
# OUTPUT: ['Welcome', 'to', 'the', 'world', 'of', 'Python'] # Example 2:
text = """Item_1
Item_2
Item_3"""
print(re.findall(r'\S+', text))
# OUTPUT: ['Item_1', 'Item_2', 'Item_3'] # Example 3:
text = "This is just a random text:\n New Line"
print(re.findall(r'\S+', text))
# OUTPUT: ['This', 'is', 'just', 'a', 'random', 'text:', 'New', 'Line']Related Tutorial: Python re.findall() – Everything You Need to Know Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video. [b]Conclusion[/b] We have successfully solved the given problem using different approaches. I hope you enjoyed this article and it helps you in your Python coding journey. Please subscribe and stay tuned for more interesting articles! Related Reads: ⦿ How To Split A String And Keep The Separators?⦿ How To Cut A String In Python? ⦿ Python | Split String into Characters Python Regex Course Google engineers are regular expression masters. The Google search engine is a massive text-processing engine that extracts value from trillions of webpages. Facebook engineers are regular expression masters. Social networks like Facebook, WhatsApp, and Instagram connect humans via text messages. Amazon engineers are regular expression masters. Ecommerce giants ship products based on textual product descriptions. Regular expressions rule the game when text processing meets computer science. If you want to become a regular expression master too, check out themost comprehensive Python regex course on the planet:
|