Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of R's paste command for vector of numbers in Python

Tags:

python

string

r

This must have been asked before, but I'm afraid I can't find the answer.

In R, I can write

paste0('s', 1:10)

which returns a list of 10 character (string) variables:

[1] "s1"  "s2"  "s3"  "s4"  "s5"  "s6"  "s7"  "s8"  "s9"  "s10"

How do I do this simply in Python? The only way I can think of is with a for loop, but there must be a simple one-liner.

I've tried things like

's' + str(np.arange(10))
['s', str(np.arange(10))]
like image 507
tsawallis Avatar asked Jan 20 '15 13:01

tsawallis


People also ask

What is paste R?

How to use the paste() function in R? A simple paste() will take multiple elements as inputs and concatenate those inputs into a single string. The elements will be separated by a space as the default option.

How do you paste a function in Python?

paste() method is used to paste an image on another image. This is where the new() method comes in handy. Parameters: image_1/image_object : It the image on which other image is to be pasted.


2 Answers

>>> ["s" + str(i) for i in xrange(1,11)]
['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9', 's10']

EDIT: range works in both Python 2 and Python 3, but in Python 2 xrange is a little more efficient potentially (it's a generator not a list). Thansk @ytu

like image 197
cdyson37 Avatar answered Oct 13 '22 11:10

cdyson37


>>> list(map('s{}'.format, range(1, 11)))
['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9', 's10']
like image 36
jamylak Avatar answered Oct 13 '22 13:10

jamylak