Python split string and get nth element

If you don't want to index the results, it's not difficult to write your own function to deal with the situation where there are either too few or two many values. Although it requires a few more lines of code to set up, an advantage is that you can give the results meaningful names instead of anonymous ones likeresults[0]andresults[2].

def splitter[s, take, sep=',', default=None]:
    r = s.split[sep]
    if len[r] < take:
       r.extend[[default for _ in xrange[take - len[r]]]]
    return r[:take]

entry = 'A,B,C'
a,b,c,d = splitter[entry, 4]
print a,b,c,d  # --> A B C None

entry = 'A,B,C,D,E,F'
a,b,c,d = splitter[entry, 4]
print a,b,c,d  # --> A B C D

Split a string and get a single element in Python #

To split a string and get a single element:

  1. Use the str.split[] method to split the string into a list.
  2. Access the list element at the specific index.
  3. Assign the result to a variable.

Copied!

my_str = 'one_two_three_four' first = my_str.split['_', 1][0] print[first] # 👉️ one second = my_str.split['_'][1] print[second] # 👉️ two third = my_str.split['_'][2] print[third] # 👉️ three last = my_str.rsplit['_', 1][-1] print[last] # 👉️ four

The first example uses the str.split[] method to get the first element from the list.

The str.split[] method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
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.

This is useful when you need to get the first element only.

Copied!

my_str = 'one_two_three_four' # 👇️ ['one', 'two_three_four'] print[my_str.split['_', 1]]

The second example uses the str.split[] method without providing a value for the maxsplit argument and accesses the list item at index 1.

Copied!

my_str = 'one_two_three_four' second = my_str.split['_'][1] print[second] # 👉️ two

Indexes in Python are zero-based, so the first item in a list has an index of 0, the second an index of 1, etc.

If you need to get the last element after splitting a string, use the str.rsplit[] method instead.

Copied!

my_str = 'one_two_three_four' last = my_str.rsplit['_', 1][-1] print[last] # 👉️ four

The rsplit method is very similar to split, but it splits from the right.

Note that we also provided a value for the maxsplit argument to split the string from the right only once.

Copied!

my_str = 'one_two_three_four' # 👇️ ['one_two_three', 'four'] print[my_str.rsplit['_', 1]]

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

Copied!

my_str = 'one_two_three_four' my_list = my_str.split['?'] print[my_list] # 👉️ ['one_two_three_four']

Chủ Đề