为什么 While 循环会在下一条语句中产生语法错误
Why is the While loop creating a syntax error on the next statement
您好,我一直在尝试在 python 2.7 中编写一个程序,该程序将单词作为输入并输出单词中的字母数。起初它在工作,但发生了一些事情,现在它不断地通过不属于 while 循环的第一行返回错误。
这是部分代码:
def number_of_letters(input):
nol = input.find(input[-1])
while input[nol:] != input[-1]:
nol = input.find(input[-1], input.find(input[-1] + 1)
nol = nol + 1
print nol
python 解释器通过我尝试在 while 块之后放置的任何内容不断返回语法错误(在本例中为 'nol = nol + 1 ')
我试过玩弄它但没有任何效果。请帮忙。
顺便说一下,如果有任何模块可以帮助这个程序,那就太好了,但我也想知道为什么这个不工作
您缺少右括号:
nol = input.find(input[-1], input.find(input[-1] + 1)) #<- add here
如果你想计算实际字母的数量,你可以使用str.isalpha
:
return sum(ch.isalpha() for ch in inp)
如果您不关心那里有哪些字符,请使用 len(inp)
。
避免将 input
作为变量名,因为它遮盖了 python 函数。
改变这个
nol = input.find(input[-1], input.find(input[-1] + 1)
至此
nol = input.find(input[-1], input.find(input[-1] + 1))
注意最后的括号。
python.
中有一个获取字符串长度的内置函数
word = "test"
length = len(word)
您好,我一直在尝试在 python 2.7 中编写一个程序,该程序将单词作为输入并输出单词中的字母数。起初它在工作,但发生了一些事情,现在它不断地通过不属于 while 循环的第一行返回错误。 这是部分代码:
def number_of_letters(input):
nol = input.find(input[-1])
while input[nol:] != input[-1]:
nol = input.find(input[-1], input.find(input[-1] + 1)
nol = nol + 1
print nol
python 解释器通过我尝试在 while 块之后放置的任何内容不断返回语法错误(在本例中为 'nol = nol + 1 ') 我试过玩弄它但没有任何效果。请帮忙。 顺便说一下,如果有任何模块可以帮助这个程序,那就太好了,但我也想知道为什么这个不工作
您缺少右括号:
nol = input.find(input[-1], input.find(input[-1] + 1)) #<- add here
如果你想计算实际字母的数量,你可以使用str.isalpha
:
return sum(ch.isalpha() for ch in inp)
如果您不关心那里有哪些字符,请使用 len(inp)
。
避免将 input
作为变量名,因为它遮盖了 python 函数。
改变这个
nol = input.find(input[-1], input.find(input[-1] + 1)
至此
nol = input.find(input[-1], input.find(input[-1] + 1))
注意最后的括号。
python.
中有一个获取字符串长度的内置函数word = "test"
length = len(word)