【问题标题】:Strings being read in as integers in Python?在 Python 中将字符串作为整数读入?
【发布时间】:2020-01-06 20:20:56
【问题描述】:

我正在编写一些代码,其中我读取了以下二进制数:

0000
0001
1000
1001
00000000
0000000
000000
00000
0000

部分代码读入输入使得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 string input integer


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-27
    • 2011-01-16
    • 2016-12-03
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多