0

Here's my code:

# Code to separate the numbers alphabets in a string and print it in a list
# If the user gives empty string, then empty list must be printed

def string_string(string1):
    number=''
    alpha=''
    empty=''

    list1=[]

    for i in (string1):

        if(i>='a' and i<='z' or i>='A' and i<="Z"):
            alpha=alpha+i
        elif(i==1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 0):
            number = number+i
        elif(i== ''):
            list1.append(empty)
        else:
            pass

    list1.append(int(number))
    list1.append(alpha)

    print(list1)

string1 = str(input())
string_string(string1)

I want the code to behave as follows:

Case 1: (separate letters from numbers)
Input: a888rudhvigk
Output: ['arudhvigk', 888]

Case 2: (empty string)
Input: (empty string)
Output: ['']

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    You can simplify this a lot by using `isdigit()` and empty-string falseness to pick out the numbers/blanks. – match Jan 24 '23 at 17:17
  • There can be a lot of ways to simplify your code. but I believe you are a beginner, so let's just fix your existing code: `if number != '': list1.append(int(number))` instead of `list1.append(int(number))` will fix it. – Sam Jan 24 '23 at 17:21
  • it is not solving the problem and we should not use built-in methods. case 2 is not satisfying case2: input: #user gives space as an input output: [''] – KIKKURU PRUDHVI YASHWANTH REDD Jan 24 '23 at 17:37
  • `elif(i==1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 0):` doesn't mean what you think it means (even apart from the fact that a string will never equal an int). It will always evaluate to `True` since `i == 1 or 2 or 3 ...` isn't equivalent to `i == 1 or i == 2 or ...` – John Coleman Jan 24 '23 at 17:40

1 Answers1

0

You can try something like this:

s = 'a888rudhvigk'
number = ''
string = ''
for i in s:
    if i.isdigit():
        number = number + i
    else:
        string = string + i
lst = [string, number]

output:  ['arudhvigk', '888']