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.
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.
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.
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.
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')
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With