string = 'Hello, welcome to my world001'
This is the string which I have been trying to split into two (number and string). The numbers from the back needs to be splitted from the original string. Is there any method in python that can do this real quick.
Here's my try(code):
length_of_string = len(string) - 1
num = []
if string[-1].isdigit():
while length_of_string > 0:
if string[length_of_string].isdigit():
num.insert(0, int(string[length_of_string]))
length_of_string -= 1
print(num)
else:
string += '1'
print(string)
To split a string into a list of integers: Use the str. split() method to split the string into a list of strings. Use the map() function to convert each string into an integer.
Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.
Method 1: Split multiple characters from string using re. split() This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.
A regex find all approach might be appropriate here. We can find groups of all non digit or all digit characters, alternatively.
string = 'Hello, welcome to my world001'
parts = re.findall(r'\D+|\d+', string)
print(parts) # ['Hello, welcome to my world', '001']
You can use itertools.groupby
with your str.isdigit
test as grouping function
from itertools import groupby
parts = ["".join(g) for _, g in groupby(string, key=str.isdigit)]
You can use a regex:
import re
string = 'Hello, welcome to my world001'
m=re.search(r'^(.*?)(\d+)$', string)
>>> m.groups()
('Hello, welcome to my world', '001')
Or use a regex split:
>>> re.split(r'(?<=\D)(?=\d+$)', string)
['Hello, welcome to my world', '001']
Alternatively, you can loop over the string in pairs and break when the first digit is seen to perform a split:
for i,(c1,c2) in enumerate(zip(string, string[1:]),1):
if c2.isdigit(): break
s1,s2=(string[0:i],string[i:])
>>> (s1,s2)
('Hello, welcome to my world', '001')
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