None of these answers generalizes to arbitrary numbers of arguments like paste
in R does. Here is a fairly faithful port of the original R function. The only thing to remember is that each element must be presented as a list, since character strings in R are actually just vectors of characters under the hood:
import itertools
def paste(*args, sep = ' ', collapse = None):
"""
Port of paste from R
Args:
*args: lists to be combined
sep: a string to separate the terms
collapse: an optional string to separate the results
Returns:
A list of combined results or a string of combined results if collapse is not None
"""
combs = list(itertools.product(*args))
out = [sep.join(str(j) for j in i) for i in combs]
if collapse is not None:
out = collapse.join(out)
return out
Usage:
paste (['s'], range(10), sep = '')
Out[62]: ['s0', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9']
paste (['s'], range(2), ['t'], range(3), sep = '')
Out[63]: ['s0t0', 's0t1', 's0t2', 's1t0', 's1t1', 's1t2']
paste (['s'], range(2), ['t'], range(3), sep = '', collapse = ':')
Out[64]: 's0t0:s0t1:s0t2:s1t0:s1t1:s1t2'
You can get paste0
by using currying:
from functools import partial
paste0 = partial(paste, sep = '')