如何解决Python 3中的“ Str不可调用”错误?

任何指导表示赞赏。我是编程新手。


问题:“ str不可调用”的运行时错误。并且,可能是语义错误。详细信息:“如果len <= 70:TypeError:'str'对象不可调用”


预期的结果:我正在尝试编写一个函数,该函数接受一个字符串,然后打印该字符串,以便该字符串的最后一个字母在显示的第70列中。


我尝试过的方法:在PEP8中运行代码,它不返回任何语法错误。删除了将str分配给s的原始行。


Python 3中的代码:


def right_justify(s):

    '''

    (string) -> string

    takes a string named s

    places it in column 70 - len of string

    '''

    s = input("Type in a word: ")

    for len in s:

        if len(s) <= 70:

            len(s) + 70 - len(s)

    return s 


print(right_justify)


鸿蒙传说
浏览 444回答 3
3回答

MYYA

如果我理解您的要求,则希望在字符串前面放置足够的空格,以便其最后一个字符在第70列中。您不需要遍历字符串。这将实现您所需要的。请注意input,函数内没有意义,因为您不能使用字符串参数来调用函数。def right_justify(s):&nbsp; &nbsp; '''&nbsp; &nbsp; (string) -> string&nbsp; &nbsp; takes a string named s&nbsp; &nbsp; places it in column 70 - len of string&nbsp; &nbsp; '''&nbsp; &nbsp; if len(s) <= 70:&nbsp; &nbsp; &nbsp; &nbsp; output = ((70 - len(s)) * " ") + s&nbsp; &nbsp; &nbsp; &nbsp; return outputinput_string = input("Type in a word: ")output_string = right_justify(input_string)print(output_string)

慕妹3242003

最简单的方法是:def right_justify(s):&nbsp; &nbsp; return "%70s" % s

万千封印

只需更换len变量还有别的。len是一个Python关键字,先生,它保留了,并不打算用作变量
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python