[英]Strings being read in as integers in Python?
我正在编写一些代码,其中读取了以下二进制数字:
0000
0001
1000
1001
00000000
0000000
000000
00000
0000
部分代码读入input,使s = input()
。 然后,我将函数定义为具有以下定义的accepts(s)
:
def accepts(str_input):
return accept_step(states[0], str_input, 0) # start in q0 at char 0
accept_step
函数定义为:
def accept_step(state, inp, pos):
if pos == len(inp): # if no more to read
return state.is_final_state # accept if the reached state is final state
c = inp[pos] # get char
pos += 1
try:
nextStates = state.transitions[c]
except():
return False # no transition, just reject
# At this point, nextStates is an array of 0 or
# more next states. Try each move recursively;
# if it leads to an accepting state return true.
"""
*** Implement your recursive function here, it should read state in nextStates
one by one, and run accept_step() again with different parameters ***
"""
for state in nextStates:
if accept_step(state, inp, pos): #If this returns true (recursive step)
return True
return False # all moves fail, return false
"""
Test whether the NFA accepts the string.
@param in the String to test
@return true if the NFA accepts on some path
"""
我收到此错误:
if pos == len(inp): # if no more to read
TypeError: object of type 'int' has no len()
我已经尝试过使用str(s)
(转换),例如在input(str(s))
和accepts(str(s))
,但无济于事。
看来,无论出于什么原因,我的输入文本都以整数而不是字符串的形式读取。
我想以字符串而不是整数的形式读取我的输入,并能够使用字符串的len()
属性执行我的程序。 有人可以指出正确的方向,并向我解释为什么我的输入是整数而不是字符串吗? 我以为如果我特别想要整数输入,就不得不使用int(input())
吗?
Python尝试假定输入变量的类型。 在这种情况下,它认为您正在输入整数。 因此,在分配期间尝试在输入周围使用str()。
s = str(input())
accepts(s)
例如,Python3中的一些测试:
>>> a = 1001
>>> isinstance(a, int)
Returns: True
>>> b = '1001'
>>> isinstance(b, int)
Returns: False
>>> c = str(1001)
>>> isinstance(c, int)
Returns: False
>>> isinstance(c, str)
Returns: True
>>> len(c)
Returns: 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.