Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using split function in python3.5

Trying to split the string at number 7 and I want 7 to be included in the second part of the split string.

Code:

a = 'cats can jump up to 7 times their tail length'

words = a.split("7")

print(words)

Output:

['cats can jump up to ', ' times their tail length']

String got split but second part doesn't include 7.

I want to know how I can include 7.

note: not a duplicate of Python split() without removing the delimiter because the separator has to be part of the second string.

like image 543
Samyak Jain Avatar asked Feb 23 '18 15:02

Samyak Jain


People also ask

How do you split in Python 3?

Python 3 - String split() MethodThe split() method returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.

What split () do in Python?

Definition and Usage. The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you implement a split function in Python?

The Split function is implemented with “\n” as the separator. Whenever the function sees a newline character, it separates the string into substrings. You can also perform split by newline character with the help of the splitlines() function.


2 Answers

A simple and naive way to do this is just to find the index of what you want to split on and slice it:

>>> a = 'cats can jump up to 7 times their tail length'
>>> ind = a.index('7')
>>> a[:ind], a[ind:]
('cats can jump up to ', '7 times their tail length')
like image 194
Rafael Barros Avatar answered Sep 26 '22 13:09

Rafael Barros


in one line, using re.split with the rest of the string, and filter the last, empty string that re.split leaves:

import re
a = 'cats can jump up to 7 times their tail length'
print([x for x in re.split("(7.*)",a) if x])

result:

['cats can jump up to ', '7 times their tail length']

using () in split regex tells re.split not to discard the separator. A (7) regex would have worked but would have created a 3-item list like str.partition does, and would have required some post processing, so no one-liner.

now if the number isn't known, regex is (again) the best way to do it. Just change the code to:

[x for x in re.split("(\d.*)",a) if x]
like image 30
Jean-François Fabre Avatar answered Sep 24 '22 13:09

Jean-François Fabre