【问题标题】:Function("last name, first name") reports: TypeError: can only concatenate str (not "int") to strFunction("last name, first name") 报告:TypeError: can only concatenate str (not "int") to str
【发布时间】:2019-10-13 13:54:31
【问题描述】:

我需要创建一个函数,该函数接受一个包含“姓氏,名字”格式的名称的字符串,并打印一条欢迎消息,其中包含名字在前,姓在最后,并告诉该人他们名字的长度.该函数应该能够处理错误的输入并打印一条消息:输入格式错误:请使用“Last_Name,First_Name”。以下是我到目前为止所拥有的以及我得到的错误。如果用户以错误的格式输入信息,我无法弄清楚如何创建错误消息:

input_name = input("Enter your name in last name, first name format")
Last_name, First_name =input_name.strip().split(',')
Full_name=First_name + ' ' + Last_name
print(Full_name + ' your first name is ' + len(First_name) + ' letters in length')

TypeError
Traceback (most recent call last)
<ipython-input-14-14516c1daf2c> in <module>()
  2 Last_name, First_name =input_name.strip().split(',')
  3 Full_name=First_name + ' ' + Last_name
----> 4 print(Full_name + ' your first name is ' + len(First_name) + ' letters in length')
TypeError: can only concatenate str (not "int") to str

【问题讨论】:

    标签: python input


    【解决方案1】:

    len() 返回一个整数 - 要将其与字符串连接,您需要先将其转换为字符串。您可以使用 str() 函数来做到这一点。

    print(Full_name + ' your first name is ' + str(len(First_name)) + ' letters in length')
    

    要回答这个问题的第二部分:如何告诉用户输入格式错误,可以做一些简单的错误处理。如果输入格式错误,该行

    Last_name, First_name =input_name.strip().split(',')
    

    可能会引发某种异常(解包的值太多,解包的值不足等)。所以你可以这样做:

    try:
        Last_name, First_name =input_name.strip().split(',')
    except:
        print("Input format is wrong")
        sys.exit(1)
    

    当然,还有更强大的方法可以做到这一点。例如,您可以:

    1) 使用正则表达式检查输入格式

    2) 拆分前检查输入字符串是否存在,

    3) 检查.split()之后的字符串数组的长度,给用户更具体的错误信息

    【讨论】:

      【解决方案2】:

      您收到此错误是因为连接 len(First_name) 会返回一个带字符串的整数。

      您可以使用正则表达式模式匹配来验证名称。

      import re
      
      def is_valid(name: str):
          pattern = re.compile(r'^\s*\w+\s*,\s*\w+\s*$')
          return pattern.match(name)
      
      
      def print_welcome_message(name: str):
          if is_valid(name):
              last_name, first_name = map(str.strip, name.split(','))
              message = f'{first_name} {last_name} your first name is {len(first_name)} letters in length'
              print(message)
          else:
              print("Input format error: please use 'Last_Name, First_Name'")
      
      if __name__ == '__main__':
          input_name = input("Enter your name in last name, first name format")
          print_welcome_message(input_name)
      

      【讨论】:

        猜你喜欢
        • 2022-11-01
        • 2020-11-21
        • 2021-08-18
        • 1970-01-01
        • 2019-02-02
        • 2020-02-29
        • 2020-09-18
        • 1970-01-01
        • 2023-02-25
        相关资源
        最近更新 更多