鱼C论坛

 找回密码
 立即注册
查看: 2138|回复: 3

[已解决]收集参数是元组吗,能和字符串相加吗

[复制链接]
发表于 2022-7-22 17:09:56 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 IT界文艺代表 于 2022-7-22 17:09 编辑

这个为什么报错。。
def Speech(*words , name):
    print(*words + '------' + name)

Speech('hello' , 'see you' , name = 'ABC')
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    Speech('hello' , 'see you' , name = 'ABC')
  File "<pyshell#46>", line 2, in Speech
    print(*words + '------' + name)
TypeError: can only concatenate tuple (not "str") to tuple
最佳答案
2022-7-22 20:16:13
本帖最后由 jackz007 于 2022-7-22 20:48 编辑

        函数的收集参数和命名可选参数是这样用的
  1. def Speech(*words , name = 'ABC') :   # 命名可选参数应该出现在函数的定义中,而不是调用时。
  2.     print(',' . join(words) + '------' + name)
复制代码

        如果这样调用函数 Speech()
  1. Speech('hello' , 'see you')  # 调用函数时,命名可选参数一般应该省略,但是,如果给出,必须要 "点名道姓"
复制代码

    那么,在 Speech() 内,接收到的参数情况是:
  1. words = ('hello' , 'see you')     # 收集参数是一个由所有普通输入参数构成的元组。
  2. name = 'ABC'
复制代码

    元组不可以与字符串相加,但是,如果把字符串作一个新元素被添加进元组是可以的
  1. words = ('hello' , 'see you')
  2. name = 'ABC'
  3. words = words + (name ,)   # words = ('hello' , 'see you' , 'ABC')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-7-22 17:16:39 | 显示全部楼层
本帖最后由 青出于蓝 于 2022-7-22 17:23 编辑


这里星号后面的参数即可以加入多个元素的元组元组不能与非元组元素相加(包括字符串)
这里’———‘是str,当然会报错

欢迎追问
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2022-7-22 18:24:37 | 显示全部楼层
用 join
  1. def Speech(*words , name):
  2.     print(''.join(words) + '------' + name)

  3. Speech('hello' , 'see you' , name = 'ABC')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2022-7-22 20:16:13 | 显示全部楼层    本楼为最佳答案   
本帖最后由 jackz007 于 2022-7-22 20:48 编辑

        函数的收集参数和命名可选参数是这样用的
  1. def Speech(*words , name = 'ABC') :   # 命名可选参数应该出现在函数的定义中,而不是调用时。
  2.     print(',' . join(words) + '------' + name)
复制代码

        如果这样调用函数 Speech()
  1. Speech('hello' , 'see you')  # 调用函数时,命名可选参数一般应该省略,但是,如果给出,必须要 "点名道姓"
复制代码

    那么,在 Speech() 内,接收到的参数情况是:
  1. words = ('hello' , 'see you')     # 收集参数是一个由所有普通输入参数构成的元组。
  2. name = 'ABC'
复制代码

    元组不可以与字符串相加,但是,如果把字符串作一个新元素被添加进元组是可以的
  1. words = ('hello' , 'see you')
  2. name = 'ABC'
  3. words = words + (name ,)   # words = ('hello' , 'see you' , 'ABC')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-27 18:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表