Hoàng Việt
Hoàng Việt

Reputation: 174

python distinguish number and string solution

I'm new to python and trying to solve the distinguish between number and string For example :

Upvotes: 1

Views: 2229

Answers (5)

pylang
pylang

Reputation: 44515

As you mentioned you are new to Python, most of the presented approaches using str.join with list comprehensions or functional styles are quite sufficient. Alternatively, I present some options using dictionaries that can help organize data, starting from basic to intermediate examples with arguably increasing intricacy.

Basic Alternative

# Dictionary
d = {"Number":"", "String":""}
for char in s:
    if char.isdigit():
        d["Number"] += char
    elif char.isalpha():
        d["String"] += char
d
# {'Number': '111111', 'String': 'aaaa'}
d["Number"]                                                # access by key
# '111111'

import collections as ct

# Default Dictionary
dd = ct.defaultdict(str)
for char in s:
    if char.isdigit():
        dd["Number"] += char
    elif char.isalpha():
        dd["String"] += char
dd

Upvotes: 0

Rahul K P
Rahul K P

Reputation: 16081

Try with isalpha for strings and isdigit for numbers,

In [45]: a = '111aa111aa'
In [47]: ''.join([i for i in a if i.isalpha()])
Out[47]: 'aaaa'
In [48]: ''.join([i for i in a if i.isdigit()])
Out[48]: '111111'

OR

In [18]: strings,numbers = filter(str.isalpha,a),filter(str.isdigit,a)

In [19]: print strings,numbers
aaaa 111111

Upvotes: 1

akash karothiya
akash karothiya

Reputation: 5950

You can use in-built functions as isdigit() and isalpha()

>>> x = '111aa111aa'
>>> number = ''.join([i for i in x if i.isdigit()])
'111111'
>>> string = ''.join([i for i in x if i.isalpha()])
'aaaa'

Or You can use regex here :

>>> x = '111aa111aa'
>>> import re
>>> numbers = ''.join(re.findall(r'\d+', x))
'111111'
>>> string = ''.join(re.findall(r'[a-zA-Z]', x))
'aaaa'

Upvotes: 3

John La Rooy
John La Rooy

Reputation: 304205

>>> my_string = '111aa111aa'
>>> ''.join(filter(str.isdigit, my_string))
'111111'
>>> ''.join(filter(str.isalpha, my_string))
'aaaa'

Upvotes: 1

Arun
Arun

Reputation: 1179

Here is your answer for numbers

import re
x = '111aa111aa'
num = ''.join(re.findall(r'[\d]+',x))

for alphabets

import re
x = '111aa111aa'
alphabets = ''.join(re.findall(r'[a-zA-Z]', x))

Upvotes: 3

Related Questions