首页 > 解决方案 > 我的带有 *args 的函数仅重制第一个参数 python,但我需要全部重制

问题描述

我需要编写一个装饰器,它从字符串的开头和结尾删除空格,这些空格就像另一个函数的参数一样给出。起初我试图只写一个使用 的函数strip,但它只在我需要它们时重新制作第一个给定的 arg。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!

要改变什么?

标签: pythonfunctionargs

解决方案


strip仅删除前导和尾随空格,并且您仅stripping 最终结果。您必须strip在每个元素之前join对它们进行 ing,这可以在列表理解中完成:

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

thestr(x)有点不必要,但我不知道,也许你会传入ints 什么的。


推荐阅读