我试图在Python中实现字符串的串联,这些字符串通过元组作为多个参数传递到函数中...我只是完全不知道如何处理多个字符串参数并使用
join
方法来放置字符串之间的 -
分隔符。例如,当我传递值 I
、Love
、Python
时,我期待看到 I-Love-Python
..
看看下面
##Define a function that takes multiple string arguments
def concatenate(*args):
#Got a problem processing the tuple elements and append delimiter - to the end of each word
#Tried using a set with its add method but it didn't work
u=len(args)#Get the length of the arguments tuple
myarray={0}#initialize a new set to length 0
for k in range(0, u):
myarray.add(args[k]+"-")#append delimiter for every tuple member
return myarray
##call concatenate with parameters and print
print(concatenate("I","Love","Python"))
更改您的代码,如下所示:
##Define a function that takes multiple string arguments
def concatenate(*args):
return "-".join(args)
##call concatenate with parameters and print
print(concatenate("I","Love","Python"))
输出:
“我爱Python”
如上面评论部分所述,您可以简单地使用 Python 的内置字符串函数,即
.join()
,来连接由分隔符分隔的多个字符串参数(在本例中为 -
)。示例:
s = '-'.join(['I','Love','Python'])
print(s)
# I-Love-Python
注意:如果您有非字符串属性,则必须先将它们转换为字符串。例如:
points = 3
s = '-'.join(['Each','player', 'has', str(points),'points'])
print(s)
# Each-player-has-3-points
如果您需要在需要多个参数的函数中执行此操作(即
*args
),那么只需 return '-'.join(args)
。再次强调,请记住首先转换所有非字符串参数。