4

I got the tuple -

Result = [
    ('80407', 'about power supply of opertional amplifier', '11 hours ago'),
    ('80405', '5V Regulator Power Dissipation', '11 hours ago')]

I want to iterate over the tuples and separate the items in the tuples by ;.

The output should be as follows -

80407;about power supply of opertional amplifier;11 hours ago

I tried the following:

for item in zip(*Result):
    print(*item[0], end=';')

Which gave me the result -

8 0 4 0 7;a b o u t   p o w e r   s u p p l y   o f   o p e r t i o n a l   a m p l i f i e r;1 1   h o u r s   a g o;

and

for item in Result:
    print(*item[0], end=';')

Which gave me -

8 0 4 0 7;8 0 4 0 5;

How to properly iterate over a tuple?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Alex_P
  • 2,580
  • 3
  • 22
  • 37

5 Answers5

5

Join the items in the tuple with a ;, and join the resultant string in the outer list with another separator, perhaps a newline \n

s = '\n'.join(';'.join(lst) for lst in Result)
print(s)

The output will be

80407;about power supply of opertional amplifier;11 hours ago
80405;5V Regulator Power Dissipation;11 hours ago
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
4

To accomplish this, no zip call is required. Instead, your could can look like this:

for item in Result:
    print(*item, sep=';')

You were attempting to use end instead of sep. end just adds a semicolon to the end of the line, instead of a newline. sep specifies what seperates the values in a print call. By default, this is a space (sep=' ') and (end='\n')

Calder White
  • 1,287
  • 9
  • 21
  • Thank you for your answer. I did not think about `sep=`. But your answer works of course as well! – Alex_P Jul 13 '19 at 14:44
4

I'd join each item in the tuple with a semicolon, and then the tuples with linebreaks:

print('\n'.join(';'.join(i) for i in Result))
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You can use %s and tuple position to achieve it.

for i in Result:
    print('%s;%s;%s'% (i[0],i[1],i[2]))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Terrence Poe
  • 634
  • 4
  • 17
0

Using single join statement

result = [
    ('80407', 'about power supply of operational amplifier', '11 hours ago'),
    ('80405', '5V Regulator Power Dissipation', '11 hours ago')]

for item in result:
  print(';'.join(item))

gives

80407;about power supply of operational amplifier;11 hours ago
80405;5V Regulator Power Dissipation;11 hours ago
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Subham
  • 397
  • 1
  • 6
  • 14