Home > OS >  Write a function that will take as input a string that includes both letters and numbers
Write a function that will take as input a string that includes both letters and numbers

Time:12-11

The function should first remove all of the letters, and then convert each digit to a single-digit integer. Finally, it should return a list with each of the integers sorted from lowest to highest.

("a2fei34bfij1") should return [1, 2, 3, 4]

("owifjaoei3oij444kfj2fij") should return [2, 3, 4, 4, 4]

("987321a") should return [1, 2, 3, 7, 8, 9]

CodePudding user response:

One of the several ways is using regex, see if this helps

import re

regex="(?P<numbers>\d)"
def filter_digits(words):
  num=[]
  if words:
    m = re.findall(regex,words)
    num=sorted([int(i) for i in m])
  return num
  
print(filter_digits("a2fei34bfij1"))
print(filter_digits("owifjaoei3oij444kfj2fij"))
print(filter_digits("987321a"))
print(filter_digits(None))
print(filter_digits("abcd"))

Reference: https://docs.python.org/3/library/re.html

CodePudding user response:

Use regex and a sort:

import re
def clean_up(input_string):
    return sorted(re.findall("[0-9]", input_string))

CodePudding user response:

Here is my solution

import re


def intList(text):
    # use regex to find every single digit in the string
    numRe = re.compile(r'\d')
    # use list comprehension to transform every found digit (which is string at first) to integer and make a list
    mo = [int(i) for i in numRe.findall(str(text))]
    # return sorted list of integers
    return sorted(mo)


print(intList("a2fei34bfij1"))  # prints [1, 2, 3, 4]
print(intList("owifjaoei3oij444kfj2fij"))  # prints [2, 3, 4, 4, 4]
print(intList("987321a"))  # prints [1, 2, 3, 7, 8, 9]
  • Related