Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into numbers and characters [duplicate]

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)
like image 863
Sunny Yadav Avatar asked Jul 12 '21 11:07

Sunny Yadav


People also ask

How do you split a string into numbers?

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.

How do I split a string into multiple parts?

Answer: You just have to pass (“”) in the regEx section of the Java Split() method. This will split the entire String into individual characters.

Can a string be split on multiple 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.


Video Answer


3 Answers

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']
like image 53
Tim Biegeleisen Avatar answered Nov 08 '22 22:11

Tim Biegeleisen


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)]
like image 44
user2390182 Avatar answered Nov 08 '22 20:11

user2390182


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')
like image 20
dawg Avatar answered Nov 08 '22 21:11

dawg