如果是python中的else命令:是否可以逐个字符地检查导致一个输出?

时间:2013-04-23 02:46:32

标签: python if-statement python-2.7

g = raw_input("What gender would you prefer Male or Female? (Please press m or f): ")
p = raw_input("Please enter your 10 digit Phone Number: ")
reasons = raw_input("Please enter your reason by pressing 1-4: ")
r = reasons
valid_mp3 = g+p+r
print valid_mp3
f12312312345

输出的形式为:性别(f)手机号码(1231231234)原因(5) 有没有办法说明:

if getFirstCharacter(valid_mp3) == 'f':
    # miscellaneous command
if getSecondCharacter(valid_mp3) == '1'
    # miscellaneous command 

如何实施getFirstCharactergetSecondCharacter

2 个答案:

答案 0 :(得分:2)

只是反对g和p,除非有某种原因你不能。

if g == 'f':
    # do something for females
else if g == 'm':
    # do something for males
else:
    # invalid input

与p的第一个字符相同:

if p[0] == '1':
    # do something for first character of '1'

如果您已经拥有拆分版本,尝试使用连接版本执行任何复杂操作都没有意义。

答案 1 :(得分:0)

你可能会使用这样的字符串索引:

if valid_mp3[0] == 'f':
    miscellaneous command
if valid_mp3[1] == '1':
    some other command