-2

Hi i am writing a code but unfortunately when i try to store multiple variables from a list or tuple into a new variable it just makes a new tuple

content=['2.0', 'Banana']
newli = content[0],'\t',content[1]
print(newli)

It should be printing like a string but it is printing as a tuple in round brackets. I need this tab spacing in between these two variables. Any help would be really appreciated.

by doing content[0]+'\t'+content[1] the tab space is not working

Actually what i wanted to achieve it so i can call this variable anywhere without using the manual print command everywhere and also to write in a file

Noob Saibot
  • 113
  • 1
  • 7
  • 2
    Possible duplicate of [Concatenate item in list to strings](https://stackoverflow.com/questions/12453580/concatenate-item-in-list-to-strings) – Georgy Jun 29 '18 at 08:38
  • Do consider using `join` instead as the last comment says. – doctorlove Jun 29 '18 at 08:41

7 Answers7

2

Replace the commas with + i.e.

newli = content[0] + '\t' + content[1]
jc1850
  • 1,101
  • 7
  • 16
2

You are not using string concatenation, but creating a tuple. You use , separation to create a tuple. You need to use + to concatenate strings.

content=['2.0', 'Banana']
newli = content[0] + '\t' + content[1]
print(newli)
AndrejH
  • 2,028
  • 1
  • 11
  • 23
1

newli is a tuple, since you're grouping values with a comma.

You should make it a string by doing this:

content=['2.0', 'Banana']
newli = content[0] + '\t' + content[1]
print(newli)
magicleon94
  • 4,887
  • 2
  • 24
  • 53
1

This is normal behavior:

a = 'first', '\t', 'second' creates a tuple containing 'first', and tab and 'second'
a = 'first', creates a tuple containing 'first'; it is the comma that makes the tuple.

If you want to concatenate the values as a string, you could do like this:

a = 'first' + '\t' + 'second'

or like this, using f-strings:

f = 'first'
m = '\t'
s = 'second'
a = f'{f}{m}{s}'
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
0

Its because you are asking for newli to store items as a tuple. Use string concatenation if you want to store them as a string

sjaymj62
  • 386
  • 2
  • 18
0

Yeah that's because you are putting comas between the strings. In python string concatenation is done with the + operator.

Try changing your code to:

content=['2.0', 'Banana']
newli = content[0] + '\t' + content[1]
print(newli)
Zuma
  • 806
  • 1
  • 7
  • 10
0

In Python values that are separated by comma (,) produces a tuple of that values. Like:

a=10
b=5
total_data = a,b
print(total_data) #this will produce a tuple (10, 5)

To get output as string you need to use + operator:

content=['2.0', 'Banana']
newli = content[0]+'\t'+content[1]
print(newli) #output: 2.0   Banana

Also you can use join function to get your expected output. Like:

content=['2.0', 'Banana']
newli = content[0],content[1]
print("\t".join(newli)) #output: 2.0   Banana
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39