【问题标题】:lower() fuction does not take argumentslower() 函数不带参数
【发布时间】:2017-08-15 05:47:09
【问题描述】:
def main():

    print("this program creates a file of usernames from a ")
    print("files of names ")
    # get the file names

    infilename = input("what files are the name in")
    outfilename = input("what file should the usernames go in")
    # open the files

    infile = open(infilename,'r')
    outfile = open(outfilename,'w')
    # process each line of the input file
    for line in infile.readlines():
        # get the first and last names from line
        first, last = line.split()
        # create the username
        uname = line.lower(first[0]+last[:7])
        # write it to the output file
        outfile.write(uname+'\n')
    # close both files
    infile.close()
    outfile.close()

    print("usernames have been written to : ", outfilename)

main()

我正在尝试编写一个程序,该程序从文件中获取一堆名字和姓氏,然后从名字的第一个字母和姓氏的其余字母的组合中打印一个用户名。示例:alex doug 将是 adoug

python 解释器在uname = line.lower(first[0]+last[:7]) 上显示错误。

TypeError lower() takes no arguments (1 given)

有没有办法解决这个错误,或者有没有其他方法可以解决这个问题?

【问题讨论】:

  • 您认为line.lower(first[0]+last[:7]) 中的line 的实际含义/作用是什么?
  • 我想从名字中获取第一个字母并在索引 7 之前获取姓氏,所以如果名字名字是 4 并且姓氏是 chan,结果将是 fchan
  • 是的,但这说明了您对 firstlast 所做的事情,而不是您对名为 line 的变量所做的事情。为什么它是命令line.lower(first[0]+last[:7]) 的一部分?
  • line 变量在循环的帮助下遍历文件中的每一行,然后使用 split 函数拆分名字和姓氏,给出错误的行基本上是生成用户名
  • 是的,但是那个变量是什么意思在那个特定的行?你为什么把它包括在那里?显然,我知道它在语法上的含义。我试图梳理出你的推理。

标签: python python-3.x lowercase


【解决方案1】:

写得正确,相关的行可能如下所示:

uname = (first[0]+last[:7]).lower()

...或者,更详细地说:

uname_unknown_case = first[0]+last[:7]
uname = uname_unknown_case.lower()

值得注意的是,用作输入的字符串是调用方法的对象;正如错误消息所说,没有其他参数。

【讨论】:

    【解决方案2】:

    lower 函数不是这样工作的。如果要在 python 中将文本转换为小写,则必须执行以下操作:

    string1 = "ABCDEFG"
    string2 = string1.lower()
    print(string2) # prints abcdefg
    

    【讨论】:

    • @ShadowRanger 感谢编辑,没有注意到它是 python 3
    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 2022-07-14
    • 2011-08-07
    • 2021-08-19
    • 2013-12-08
    • 2015-04-26
    • 1970-01-01
    相关资源
    最近更新 更多