Python编程(python 2.7.10):IF循环

时间:2017-09-23 05:45:43

标签: python-2.7 loops if-statement

我在Python 2.7.10中完成了一个程序来查找给定位置的字符。然而,IF循环似乎存在问题......

n= raw_input() #input string
print(n)
t= raw_input() #position of the character in the string to be retrieved
for i in range(0,10):
  if i == t;
    print(n[i-1])

输出:

 hey
hey
 1

我已经在repl.it中执行了这个程序。在迭代期间,IF循环检查值i是否取字符值' t'而不是存储要获得的角色的位置的变量t ..关于如何解决这个问题的任何想法?

2 个答案:

答案 0 :(得分:0)

将变量t用作int。 raw_input将返回一个字符串。您必须将其转换为int。试试这个

n= raw_input() #input string
print(n)
t= raw_input() #position of the character in the string to be retrieved
for i in range(0,10):
  if i == int(t):
    print(n[i-1])

我不知道你要做什么,但是从输入位置获得角色的最佳方式是,

n= raw_input() #input string
print(n)
t= int(raw_input())
print(n[t-1])

答案 1 :(得分:0)

如果您的要求与您在问题中提到的那样,则不需要for循环:

n= raw_input("Enter a string:") #input string
print("You entered: {}".format(n))
t= int(raw_input("Enter a positionf of the character to be retrieved:")) #position of the character in the string to be retrieved
if t < 1 or t > len(n):
    print ("Not found.")
else:
    print ("You asked for: {} at index {}".format(n[t-1], t))