Equivalent to R paste command for a vector of numbers in Python

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 to do this simply in Python? The only way I can think of is with a for loop, but there should be a simple single line.

I tried things like

 's' + str(np.arange(10)) ['s', str(np.arange(10))] 
+6
source share
3 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 works a little more efficiently (this generator is not a list). Thansk @ytu

+12
source

The answer cdyson37 is the most pythonic; of course you can use range rather than xrange in your case.

In Python2, you can also pay more attention to the functional style with something like:

 map(lambda x: "s"+str(x), range(1,11)) 
+5
source
 >>> map('s{}'.format, range(1, 11)) ['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9', 's10'] 
+5
source

Source: https://habr.com/ru/post/981278/


All Articles