【问题标题】: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编写一个 python 程序,它将一个字符串作为用户的输入。输入字符串应包含字母和数字的组合
【发布时间】:2021-11-09 14:14:06
【问题描述】:

编写一个 python 程序,它将一个字符串作为用户的输入。输入字符串应该包含字母和数字的组合。然后,您的任务是识别该输入字符串中的数字并将这些数字存储在列表中。最后,对列表进行排序并打印排序后的列表和数字的总和作为输出给用户。

样本输入 1 m4gt567q09y2

样本输出 1 ['0', '2', '4', '5', '6', '7', '9']

33

示例输入 2 954217

示例输出 2 字符串中没有字母。

我尝试做到这一点。我的代码只能满足第一个示例输入。但我想不出任何方法来满足示例输入 2。我在下面提供了我的代码

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)

【问题讨论】:

  • 你可以检查 output_list 是否与输入的长度相同
  • Reopened as the target is "How do you check in python string是否只包含数字?",而这个问题是"How to find number in a必须包含字母字符的字符串?”

标签: python arrays python-3.x list python-2.7


【解决方案1】:

str.isalpha() 方法将返回 True 是一个全是字母字符的字符串,如果一个字符串全是数字,str.isdigit() 方法将返回 True

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.")

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 2016-04-30
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    相关资源
    最近更新 更多