当用户给出一个单词时如何打印?

2024-06-28 19:37:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题可以理解如下:

goodvalue=False
while (goodvalue==False):
   try:
      word=str(input("Please enter a word: "))
   except ValueError:
       print ("Wrong Input...")
   else:
       goodvalue=True

word=word.lower()
List=list(map(str,word))
lenList=len(list(map(str,word)))
listofans=[]
x=0
while (lenList-1==x):
    if List[x]==str("a"):
        listofans[x]=str("1")
        x=x+1
    elif List[x]==str("b"):
        listofans[x]=str("2")
        x=x+1
    elif List[x]==str("c"):
        listofans[x]=str("3")
        x=x+1

所有字母表都是这样持续了一段时间。。。然后:

sumofnums=listofans[0]       
y=1
while (lenList-2==y):
    sumofnums+=listofans[y]

print ("The number is: ", sumofnums)

所以基本上,如果我打招呼,它应该返回8 5 12 15。感谢您的帮助!你知道吗


Tags: falsemapinputlistwordprinttryelif
3条回答

您的代码非常凌乱,有些甚至不需要(不需要使用map)。也不是try/except结构)

为什么不简化一点;)。你知道吗

>>> import string
>>> d = {j:i for i, j in enumerate(string.lowercase, 1)}
>>> for i in 'hello':
...     print d[i],
... 
8 5 12 12 15

代码中的一些问题:

  • Don't compare booleans like that。只要做while goodvalue

  • List=list(map(str,word))过量。需要一个简单的List = list(word),但您甚至可能不需要它,因为您可以遍历字符串(如我上面所示)

  • str("a")毫无意义。"a"已经是一个字符串,因此str()在这里什么也不做。

  • 正如我之前所说,不需要try/except。没有输入会导致ValueError。(除非你的意思是int()

试试这个:

goodvalue=False
while (goodvalue==False):
   try:
      word=str(input("Please enter a word: "))
   except ValueError:
       print ("Wrong Input...")
   else:
       goodvalue=True

word=word.lower()
wordtofans=[]

for c in word:
    if c >= 'a' and c <= 'z':
        wordtofans.append( int(ord(c)-ord('a')+1) )

print wordtofans

您可以直接在for循环中迭代字符串,而不必将字符串转换为列表。你知道吗

这里有一个控制检查,以确保只有字母a..z和a..z被转换成数字。你知道吗

从字符串字母到数字的转换是使用int(ord(c)-ord('a')+1)完成的,它使用ord函数为提供的字符返回ASCII值。你知道吗

你在找这样的东西吗?你知道吗

[ord(letter)-ord('a')+1 for letter in word]

对于“hello”,输出:

[8, 5, 12, 12, 15]

ord函数返回字母的ascii序数值。减去ord('a')会将其重设为0,但“a”映射为1,因此必须按1进行调整。你知道吗

相关问题 更多 >