Python partition vs split

split() vs. partition()

In Python, we can split the string by using the following methods. Let’s look at these methods in detail.

1. split()
2. rsplit()
3. splitlines()
4. partition()
5. rpartition()
6. re.split()
7. Differences between split() and partition()
8. Conclusion
9. Resources

split()

“Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1 , then there is no limit on the number of splits (all possible splits are made).”

— Python docs

Example 1: If a sep (delimiter) isn’t mentioned, it’ll split the string based on the whitespaces in the string

a="Hello Python"
print (a.split())
#Output:['Hello', 'Python']

Example 2: If a sep (delimiter) is mentioned, it’ll split based on the occurrences of the delimiter

colors='red-green-blue-yellow'
print (colors.split("-"))
#Output:['red', 'green', 'blue', 'yellow']

Example 3

a="three times by three makes nine"
print (a.split(sep="three"))
#Output:['', ' times by ', ' makes nine']

Example 4: A maxsplit is mentioned

If maxsplit is mentioned as 1 , it’ll split on the first occurrence only.
If maxsplit is given as 2 , it’ll split on the first two occurrences only.

colors="red-orange-yellow-purple"

print (colors.split("-",maxsplit=1))
#Output:['red', 'orange-yellow-purple']

print (colors.split("-",maxsplit=2))
#Output:['red', 'orange', 'yellow-purple']

Источник

Читайте также:  Минисайт

Python Split String – How to Split a String into a List or Array in Python

Shittu Olumide

Shittu Olumide

Python Split String – How to Split a String into a List or Array in Python

In this article, we will walk through a comprehensive guide on how to split a string in Python and convert it into a list or array.

We’ll start by introducing the string data type in Python and explaining its properties. Then we’ll discuss the various ways in which you can split a string using built-in Python methods such as split() , splitlines() , and partition() .

Overall, this article should be a useful resource for anyone looking to split a string into a list in Python, from beginners to experienced programmers.

What is a String in Python?

A string is a group of characters in Python that are encased in single quotes ( ‘ ‘ ) or double quotes ( » » ). This built-in Python data type is frequently used to represent textual data.

Since strings are immutable, they cannot be changed once they have been created. Any action that seems to modify a string actually produces a new string.

Concatenation, slicing, and formatting are just a few of the many operations that you can perform on strings in Python. You can also use strings with a number of built-in modules and functions, including re , str() , and len() .

There’s also a wide range of string operations, including split() , replace() , and strip() , that are available in Python. You can use them to manipulate strings in different ways.

Let’s now learn how to split a string into a list in Python.

How to Split a String into a List Using the split() Method

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.

myString = "Hello world" myList = myString.split() print(myList) 

In this example, we split the string «Hello world» into a list of two elements, «Hello» and «world» , using the split() method.

How to Split a String into a List Using the splitlines() Method

The splitlines() method is used to split a string into a list of lines, based on the newline character (\n) .

myString = "hello\nworld" myList = myString.splitlines() print(myList) 

In this example, we split the string «hello\nworld» into a list of two elements, «hello» and «world» , using the splitlines() method.

How to Split a String into a List Using Regular Expressions with the re Module

The re module in Python provides a powerful way to split strings based on regular expressions.

import re myString = "hello world" myList = re.split('\s', myString) print(myList) 

In this example, we split the string «hello world» into a list of two elements, «hello» and «world» , using a regular expression that matches any whitespace character (\s) .

How to Split a String into a List Using the partition() Method

The partition() method splits a string into three parts based on a separator and returns a tuple containing these parts. The separator itself is also included in the tuple.

myString = "hello:world" myList = myString.partition(':') print(myList) 

In this example, we split the string «hello:world» into a tuple of three elements, «hello» , «:» , and «world» , using the partition() method.

Note: The most common method for splitting a string into a list or array in Python is to use the split() method. This method is available for any string object in Python and splits the string into a list of substrings based on a specified delimiter.

When to Use Each Method

So here’s an overview of these methods and when to use each one for quick reference:

  1. split() : This is the most common method for splitting a text into a list. You can use this method when you want to split the text into words or substrings based on a specific delimiter, such as a space, comma, or tab.
  2. partition() : This method splits a text into three parts based on the first occurrence of a delimiter. You can use this method when you want to split the text into two parts and keep the delimiter. For example, you might use partition() to split a URL into its protocol, domain, and path components. The partition() method returns a tuple of three strings.
  3. splitlines() : This method splits a text into a list of strings based on the newline characters ( \n ). You can use this method when you want to split a text into lines of text. For example, you might use splitlines() to split a multiline string into individual lines.
  4. Regular expressions: This is a more powerful method for splitting text into a list, as it allows you to split the text based on more complex patterns. For example, you might use regular expressions to split a text into sentences, based on the presence of punctuation marks. The re module in Python provides a range of functions for working with regular expressions.

Conclusion

These are some of the most common methods to split a string into a list or array in Python. Depending on your specific use case, one method may be more appropriate than the others.

Let’s connect on Twitter and on LinkedIn. You can also subscribe to my YouTube channel.

Источник

Python tip 25: split and partition string methods

The split() method splits a string based on the given substring and returns a list . By default, whitespace is used for splitting and empty elements are discarded.

>>> greeting = ' \t\r\n have a nice \r\v\t day \f\v\r\t\n ' >>> greeting.split() ['have', 'a', 'nice', 'day'] 

You can split the input based on a specific string literal by passing it as an argument. Here are some examples:

>>> creatures = 'dragon][unicorn][centaur' >>> creatures.split('][') ['dragon', 'unicorn', 'centaur'] # empty elements will be preserved in this case >>> ':car::jeep::'.split(':') ['', 'car', '', 'jeep', '', ''] 

The maxsplit argument allows you to restrict the number of times the input string should be split. Use rsplit() if you want to split from right to left.

# split once >>> 'apple-grape-mango-fig'.split('-', maxsplit=1) ['apple', 'grape-mango-fig'] # match the rightmost occurrence >>> 'apple-grape-mango-fig'.rsplit('-', maxsplit=1) ['apple-grape-mango', 'fig'] >>> 'apple-grape-mango-fig'.rsplit('-', maxsplit=2) ['apple-grape', 'mango', 'fig'] 

The partition() method will give a tuple of three elements — portion before the leftmost match, the separator itself and the portion after the split. You can use rpartition() to match the rightmost occurrence of the separator.

>>> marks = 'maths:85' >>> marks.partition(':') ('maths', ':', '85') # last two elements will be empty if there is no match >>> marks.partition('=') ('maths:85', '', '') # match the rightmost occurrence >>> creatures = 'dragon][unicorn][centaur' >>> creatures.rpartition('][') ('dragon][unicorn', '][', 'centaur') 

See my Understanding Python re(gex)? ebook to learn about string splitting with regular expressions.

📰 Use this link for the Atom feed.
✅ Follow me on Twitter, GitHub and Youtube for interesting tech nuggets.
📧 Subscribe to learnbyexample weekly for programming resources, tips, tools, free ebooks and more (free newsletter, delivered every Friday).

Источник

Оцените статью