Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python variable + itself

This maybe a very easy one but I'm unsure what to search for.

I want to do something like this:

temp = ""
for item in instance:
    temp = temp + item

I think I have seen it done like this before:

temp ++ item

but that does not work.

like image 740
GrantU Avatar asked Apr 30 '26 11:04

GrantU


2 Answers

A ++ operator does not exist in Python, but it does have the += operator. You can use it as follows:

temp = ''
for item in instance:
    temp += item

In general, strings are immutable in Python (i.e., they cannot be changed). However, as Fenikso pointed out in the comments, this operator will create a new string object consisting of the old value of temp plus the new value of item.

You will probably be faster if you use a list comprehension, such as the one Alex Parakhnevich suggests in his answer.

like image 195
Daniel Avatar answered May 03 '26 00:05

Daniel


This will suit your needs:

temp = ''.join(instance)

Documentation on join method of str: link.

Here's an example console log to be more clear:

>>> temp = ''

>>> instance = ['one', 'two', 'three']

>>> temp = ' '.join(instance)

>>> temp
>>> 'one two three'
like image 37
Alex Parakhnevich Avatar answered May 02 '26 23:05

Alex Parakhnevich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!