najis
najis

Reputation: 19

How to separate number and ascii character from string?

Let me keep it simple, I have a string that I want it from "10fo22baar" into ["1022","fobaar"] or ["10","fo","22","baar"] Is there a way to do something like that in Python 3 or 2?

Upvotes: 1

Views: 634

Answers (5)

Artur Joaquim
Artur Joaquim

Reputation: 1

1-First, we would have to do a for to go through the entire string.

2-After that to check if the character is a number or not, we could use two methods:

string.isnumeric() or string.isalpha()

3-After checking, we separate the characters into lists and format them to our liking.

Our code looks like this:

myString = '10fo22baar'
charString = []
charNum = []

for char in myString:
    if char.isnumeric():
        charNum.append(char)
    else:
        charString.append(char)

myString = [''.join(charNum), ''.join(charString)] 
print(myString)

Upvotes: 0

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

Part 1: You can use filter with str.isdigit() to filter numeric characters as:

>>> my_str = "10fo22baar"
>>> ''.join(filter(str.isdigit, my_str))
'1022'

To get non-numeric, you can use itertools.filterfalse():

>>> from itertools import filterfalse

>>> ''.join(filterfalse(str.isdigit, my_str))
'fobaar'

# OR, for older python versions, use list comprehension:
# ''.join(c for c in my_str if not c.isdigit())

Store above values in list to get list of your desired format.

Alternatively, you can also use regex to filter out digits and alphabets into separate lists as:

import re
my_str = "10fo22baar"

# - To extract digits, use expressions as "\d+"
# - To extract alphabets, use expressions as "[a-zA-Z]+"

digits = ''.join(re.findall('\d+', my_str))
# where `digits` variable will hold string:
#    '1022'

alphabets = ''.join(re.findall('[a-zA-Z]+', my_str))
# where `alphabets` variable will hold string:
#    'fobaar'

# Create your desired list from above variables:
# my_list = [digits, alphabets]

You can simplify above logic in one-line as:

my_regex = ['\d+', '[a-zA-Z]+']

my_list = [''.join(re.findall(r, my_str)) for r in my_regex]
# where `my_list` will give you:
#   ['1022', 'fobaar']

Part 2: You can use itertools.groupby() to get your second desired format of list with digits and alphabets grouped together maintaining the ordwe in single list as:

from itertools import groupby

my_list = [''.join(x) for _, x in groupby(my_str, str.isdigit)]
# where `my_list` will give you:
#    ['10', 'fo', '22', 'baar']

Upvotes: 1

Cyrus
Cyrus

Reputation: 681

Here's a simple and easy to understand solution.

mystring = '10fo22baar'
nums = []
chars = []

for char in mystring:

    if char in ['0','1','2','3','4','5','6','7','8''9']:

        nums.append(char)
    else:

        chars.append(char)

How it works:

  1. We start with mystring set to the string we want to read.
  2. We define two new lists for our numbers and regular chars.
  3. We loop through each char in mystring.
  4. If the current char of the loop iteration is a number, we append it to the number list.
  5. If it's not a number, it must be a normal char. We append it to chars.
  6. That's it

Upvotes: 0

owlynx
owlynx

Reputation: 1

Using string methods:

s = "10fo22baar"
num = ""
string = ""
for char in s:
    if char.isnumeric():
        num += str(char) 
    else:
        string += str(char)
print(num, string)

Gives ('1022', 'fobaar')

Upvotes: 0

Adrian BUdjekmd
Adrian BUdjekmd

Reputation: 59

You could try to make a for loop. Like this:

str = "10fo22baar"
nums = []
chars = []

for char in str:
    try:
        int(char)
        nums.append(char)
    except ValueError:
        chars.append(char)


sep = ["".join(nums), "".join(chars)]
print(sep)

Output would be: ['1022', 'fobaar']

Upvotes: 1

Related Questions