Python split one time

split¶

Returns a list of the words in the string, separated by the delimiter string.

Syntax¶

str. split([sep[, maxsplit]])

sep Optional. Character dividing the string into split groups; default is space. maxsplit Optional. Number of splits to do; default is -1 which splits all the items.

Return Value¶

Time Complexity¶

Remarks¶

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example,

returns [‘1’, ‘’, ‘2’]). The sep argument may consist of multiple characters (for example,

returns [‘1’, ‘2’, ‘3’]). Splitting an empty string with a specified separator returns [‘’].

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

Example 1¶

>>> ' a b c '.split() ['a', 'b', 'c'] >>> ' a b c '.split(None) ['a', 'b', 'c'] >>> ' a b c '.split(' ', 1) ['', 'a b c '] >>> ' a b c '.split(' ', 2) ['', 'a', 'b c '] >>> ' a b c '.split(' ', 3) ['', 'a', 'b', 'c '] >>> ' a b c '.split(' ', 4) ['', 'a', 'b', 'c', ''] >>> ' a b c '.split(' ', 5) ['', 'a', 'b', 'c', ''] 

Example 2¶

>>> '-a-b-c-'.split('-') ['', 'a', 'b', 'c', ''] >>> '-a-b-c-'.split('-', 1) ['', 'a-b-c-'] >>> '-a-b-c-'.split('-', 2) ['', 'a', 'b-c-'] >>> '-a-b-c-'.split('-', 3) ['', 'a', 'b', 'c-'] >>> '-a-b-c-'.split('-', 4) ['', 'a', 'b', 'c', ''] >>> '-a-b-c-'.split('-', 5) ['', 'a', 'b', 'c', ''] 

Example 3¶

>>> '----a---b--c-'.split('-') ['', '', '', '', 'a', '', '', 'b', '', 'c', ''] >>> '----a---b--c-'.split('-', 1) ['', '---a---b--c-'] >>> '----a---b--c-'.split('-', 2) ['', '', '--a---b--c-'] >>> '----a---b--c-'.split('-', 3) ['', '', '', '-a---b--c-'] >>> '----a---b--c-'.split('-', 4) ['', '', '', '', 'a---b--c-'] >>> '----a---b--c-'.split('-', 5) ['', '', '', '', 'a', '--b--c-'] >>> '----a---b--c-'.split('-', 6) ['', '', '', '', 'a', '', '-b--c-'] 

See Also¶

rsplit() for version that splits from the right

Читайте также:  Document

© Copyright 2015, Jakub Przywóski. Revision 9a3b94e7 .

Versions latest Downloads pdf htmlzip epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

Python split one time

Last updated: Feb 19, 2023
Reading time · 4 min

banner

# Table of Contents

# Split a string and get the First element in Python

To split a string and get the first element:

Copied!
my_str = 'bobby_hadz_com' first = my_str.split('_', 1)[0] print(first) # 👉️ 'bobby'

split string and get first element

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

Name Description
separator Split the string into substrings on each occurrence of the separator
maxsplit At most maxsplit splits are done (optional)

When the maxsplit argument is set to 1 , at most 1 split is done.

Copied!
my_str = 'a_b_c_d' # 👇️ ['a', 'b_c_d'] print(my_str.split('_', 1))

Python indexes are zero-based, so the first character in a string has an index of 0 , and the last character has an index of -1 or len(a_string) — 1 .

If the separator is not found in the string, a list containing only 1 element is returned.

Copied!
my_str = 'abcd' first = my_str.split('_', 1)[0] print(first) # 👉️ 'abcd'

# Removing the leading and trailing separator before splitting

If your string starts with the specific separator, you might get a confusing result.

Copied!
my_str = '_a_b_c_d_' # 👇️ ['', 'a_b_c_d_'] print(my_str.split('_', 1)) first = my_str.split('_', 1)[0] print(repr(first)) # 👉️ ""

remove leading and trailing separator before splitting

You can use the str.strip() method to remove the leading or trailing separator.

Copied!
my_str = '_a_b_c_d_' # 👇️ ['a', 'b_c_d'] print(my_str.strip('_').split('_', 1)) first = my_str.strip('_').split('_', 1)[0] print(first) # 👉️ "a"

We used the str.strip() method to remove any leading or trailing underscores from the string before calling the split() method.

# Split a string and get the Last element in Python

To split a string and get the last element:

  1. Use the str.rsplit() method to split the string from the right.
  2. Set the maxsplit argument to 1.
  3. Access the list element at index -1 .
Copied!
my_str = 'bobby,hadz,com' last = my_str.rsplit(',', 1)[-1] print(last) # 👉️ 'com'

split string and get last element

We used the rsplit() method to split the string from the right.

The str.rsplit method returns a list of the words in the string using the provided separator as the delimiter string.

Copied!
my_str = 'bobby hadz com' print(my_str.rsplit(' ')) # 👉️ ['bobby', 'hadz', 'com'] print(my_str.rsplit(' ', 1)) # 👉️ ['bobby hadz', 'com']

The method takes the following 2 arguments:

Name Description
separator Split the string into substrings on each occurrence of the separator
maxsplit At most maxsplit splits are done, the rightmost ones (optional)

Except for splitting from the right, rsplit() behaves like split() .

When the maxsplit argument is set to 1 , at most 1 split is done.

The last step is to access the last element in the list by accessing the list item at index -1 .

Copied!
my_str = 'bobby,hadz,com,abc' last = my_str.rsplit(',', 1)[-1] print(last) # 👉️ 'abc'

Python indexes are zero-based, so the first character in a string has an index of 0 , and the last character has an index of -1 or len(a_string) — 1 .

# Split a string and get the Last element using split()

You can also use the str.split() method in a similar way.

Copied!
my_str = 'bobby-hadz-com' last = my_str.split('-')[-1] print(last) # 👉️ 'com'

split string and get last element using split

If your string ends with the specific separator, you might get a confusing result.

Copied!
my_str = 'bobby-hadz-com-' last = my_str.rsplit('-', 1)[-1] # 👇️ ['bobby-hadz-com', ''] print(my_str.rsplit('-', 1)) print(last) # 👉️ ""

You can use the str.strip() method to remove the leading or trailing separator.

Copied!
my_str = 'bobby-hadz-com-' last = my_str.strip('-').rsplit('-', 1)[-1] print(last) # 👉️ "com"

We used the str.strip() method to remove any leading or trailing hyphens from the string before calling the rsplit() method.

# Split a string and get the First element using partition()

You can also use the str.partition() method to split a string and get the first element.

Copied!
my_str = 'bobby-hadz-com' result = my_str.partition('-')[0] print(result) # 👉️ bobby

The str.partition method splits the string at the first occurrence of the provided separator.

Copied!
my_str = 'bobby!hadz!com' separator = '!' # 👇️ ('bobby', '!', 'hadz!com') print(my_str.partition(separator))

The method returns a tuple containing 3 elements — the part before the separator, the separator, and the part after the separator.

If the separator is not found in the string, the method returns a tuple containing the string, followed by 2 empty strings.

Copied!
my_str = 'bobby-hadz-com' # 👇️ ('bobby-hadz-com', '', '') print(my_str.partition('!'))

In our case, the expression would return the entire string if the separator is not contained in the string.

Copied!
my_str = 'bobby-hadz-com' result = my_str.partition('!')[0] print(result) # 👉️ bobby-hadz-com

# Split a string and get the Last element using rpartition()

You can also use the str.rpartition method to split a string and get the last element.

Copied!
my_str = 'bobby-hadz-com' result = my_str.rpartition('-')[-1] print(result) # 👉️ com

The str.rpartition method splits the string at the last occurrence of the provided separator.

Copied!
my_str = 'bobbyhadz.com/articles/python' result = my_str.rpartition('/')[2] print(result) # 👉️ 'python' # 👇️ ('bobbyhadz.com/articles', '/', 'python') print(my_str.rpartition('/'))

The method returns a tuple containing 3 elements — the part before the separator, the separator, and the part after the separator.

If the separator is not found in the string, the method returns a tuple containing two empty strings, followed by the string itself.

Copied!
my_str = 'bobby-hadz-com' # 👇️ ('', '', 'bobby-hadz-com') print(my_str.rpartition('!'))

Accessing the tuple at an index of -1 would return the entire string if the separator is not contained in the string.

Copied!
my_str = 'bobby-hadz-com' result = my_str.rpartition('1')[-1] print(result) # 👉️ bobby-hadz-com

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • How to Split a string by Tab in Python
  • Split a string into fixed-size chunks in Python
  • Split a String into a List of Integers in Python
  • Split a String into multiple Variables in Python
  • Split a String into Text and Number in Python
  • How to convert a String to a Tuple in Python
  • Split a string with multiple delimiters in Python
  • Split a String by Newline characters in Python
  • How to Split a string by Whitespace in Python
  • How to Split a string on Uppercase Letters in Python
  • Split a String, Reverse it and Join it back in Python
  • Split a string without removing the delimiter in Python
  • Split a String into a List of Characters in Python
  • Flake8: f-string is missing placeholders [Solved]
  • ValueError: DataFrame constructor not properly called [Fix]

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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