Home > Software design >  Write a python program that will take a string as input from the user. The input string should have
Write a python program that will take a string as input from the user. The input string should have

Time:09-17

Write a python program that will take a string as input from the user. The input string should have a combination of BOTH the alphabets and the digits. Then, your task is to identify the digits from that input string and store those digits in a list. Finally, sort the list and print the sorted list and the sum of digits as output to the user.

Sample input 1 m4gt567q09y2

Sample Output 1 ['0', '2', '4', '5', '6', '7', '9']

33

Sample input 2 954217

Sample output 2 There's no alphabet in the string.

I tried doing this far. my code can only satisfy the 1st sample input.But I can't figure out any way to satisfy the sample input 2. I have provided my code below

string1=input("Enter the string: ")
output_list=[] 
sum=0
flag= False
for i in range(len(string1)):
   if string1[i].isdigit():
       output_list.append(string1[i])

output_list.sort()
print(output_list)
for i in output_list:
    sum =int(i)
print(sum)

CodePudding user response:

The str.isalpha() method will return True is a string is all alphabetical characters, and the str.isdigit() method will return True if a string is all digits:

string1 = input("Enter the string: ")
if any(map(str.isalpha, string1)):
    output_list = [i for i in string1 if i.isdigit()]
    print(sorted(output_list))
    print(sum(map(int, output_list)))
else:
    print("There's no alphabet in the string.")
  • Related