سؤال

I want to convert the series

tt = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024]

into

output = ['Cal 2015', 'Cal 2016', ...]

I know that in R I can simply write as:

paste('Cal',2015:2024,sep = " ")

However in Python when I tried

'Cal' + str(tt)

The result is

'Cal[2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024]'

Does anyone know how to do the string concatenation? Thanks in advance!

لا يوجد حل صحيح

نصائح أخرى

Edit:

If you must use a for-loop, you can do this:

>>> tt = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024]
>>> lst = []
>>> for t in tt:
...     lst.append("Cal {}".format(t))
...
>>> lst
['Cal 2015', 'Cal 2016', 'Cal 2017', 'Cal 2018', 'Cal 2019', 'Cal 2020', 'Cal 2021', 'Cal 2022', 'Cal 2023', 'Cal 2024']
>>>


Use a list comprehension and str.format:

>>> tt = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024]
>>> ["Cal {}".format(t) for t in tt]
['Cal 2015', 'Cal 2016', 'Cal 2017', 'Cal 2018', 'Cal 2019', 'Cal 2020', 'Cal 2021', 'Cal 2022', 'Cal 2023', 'Cal 2024']
>>>

Alternative to iCodez's solution.

>>>l=["Cal"+str(i) for i in tt]

An alternative way of using for loop without creating a new list:

tt = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024]
for i,x in enumerate(tt):
    tt[i] = 'Cal ' + str(x)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top