python - 如何测试每个特定的数字或字符

标签 python string function if-statement input

我想接收用户输入的 5 位数字,然后为每个特定数字打印一些内容。

例如,如果用户输入 12345,我想先为 1 打印一个特定的输出,然后为 2 打印另一个输出,等等。

我该怎么做呢?如果可能的话,我更愿意创建一个函数。

#!/usr/bin/python3

zipcode = int(raw_input("Enter a zipcode: "))

if zipcode == 1:
       print ":::||"
elif zipcode == 2:
       print "::|:|"
elif zipcode == 3:
       print "::||:"
elif zipcode == 4:
       print ":|::|"
elif zipcode == 5:
       print ":|:|:"
elif zipcode == 6:
       print ":||::"
elif zipcode == 7:
       print "|:::|"
elif zipcode == 8:
       print "|::|:"
elif zipcode == 9:
       print "|:|::"
elif zipcode == 0:
       print "||:::"

最佳答案

你可以使用 dictionary然后遍历输入:

zipcode = raw_input("Enter a zipcode: ")

codes={1:":::||",2:"::|:|",3:"::||:",4:":|::|",5:":|:|:",6:":||::",7:"|:::|",8:"|::|:",9:"|:|::",0:"||:::"}

for num in zipcode:
    print codes[int(num)], #add a comma here if you want it on the same line

这会给你:

>>> 
Enter a zipcode: 54321
:|:|: :|::| ::||: ::|:| :::||

编辑:

没有空格:

zipcode = raw_input("Enter a zipcode: ")

codes={1:":::||",2:"::|:|",3:"::||:",4:":|::|",5:":|:|:",6:":||::",7:"|:::|",8:"|::|:",9:"|:|::",0:"||:::"}

L = [] #create a list

for num in zipcode:
    L.append(codes[int(num)]) #append the values to a list

print ''.join(L) #join them together and then print

现在这将打印:

>>> 
Enter a zipcode: 54321
:|:|::|::|::||:::|:|:::||

关于python - 如何测试每个特定的数字或字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29722807/

相关文章:

java - "text"和新字符串 ("text"之间有什么区别?

c# - UTF8Encoding string to byte[] 转换意外行为

c - C程序中函数的定义

php - 函数内声明函数的作用域

javascript - typeof 运算符未按预期运行

python - 如何在 PLOTLY 直方图中将 x 轴更改为对数

python - 窗口图标不显示

javascript - JS - 撇号 - 不会被替换

python - 如何为 Celery 任务实现自动重试

python - 数据框中对象值的 KeyError