我的带有*args的函数只重新生成python的第一个参数,但我需要将它们全部重新生成

2024-09-23 16:32:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个decorator,它删除strig开头和结尾的空格,这些空格就像另一个函数的参数一样给出。起初,我试图只编写一个使用strip的函数,但当我需要所有参数时,它只重新生成第一个给定的参数join需要,因为如果没有它,函数将返回元组

def NewFunc(*strings):
    newstr = ' '.join([str(x) for x in strings])
    return newstr.strip()

print(NewFunc('         Anti   ', '     hype   ', '   ajou!   '))

它返回:Anti hype ajou!

当我需要时:Anti hype ajou!

改变什么


Tags: 函数参数结尾decorator元组strip空格join
1条回答
网友
1楼 · 发布于 2024-09-23 16:32:46

strip只删除前导和尾随空格,您只stripping最终结果。在对每个元素进行join运算之前,必须对其进行strip运算,这可以在列表中完成:

def NewFunc(*strings):
    newstr = ' '.join([str(x).strip() for x in strings])
    return newstr

这个str(x)有点不必要,但我不知道,也许你会通过int什么的

相关问题 更多 >