0

Suppose I have a list:

row = [u'28d07ef48e40', u'373ac79f615f', u'a3ec4faddbec', u'c0195f9568c6', u'cc4ebc7b826c', u'ccdfdb826c', u'cc4fa826c', u'cc4eeesb826c', u'ccfesb826c']

my print is

fw.write("%s %s <%s> [%s] %s %s (%s) %s: %s" %(str(row[0]),str(row[1]),str(row[2]),str(row[3]),str(row[4]),str(row[5]),str(row[6]),str(row[7]),str(row[8])))

How can I simplify this python print?

Sociopath
  • 13,068
  • 19
  • 47
  • 75
kingboli
  • 13
  • 2
  • Duplicate of https://stackoverflow.com/questions/899103/writing-a-list-to-a-file-with-python – Konrad Dec 26 '18 at 09:39
  • 1
    First step would be to remove the unnecessary `str()` calls. – Klaus D. Dec 26 '18 at 09:40
  • 1
    Also, `*row` will save you `row[0],row[1],row[2]...` – kabanus Dec 26 '18 at 09:41
  • You are not specifying that you are writing to a file. What you are doing is not printing. Why do you need some entries of the list in brackets and others not? What is the real goal here? – gosuto Dec 26 '18 at 09:42

4 Answers4

1

you can try using the join function

row = [u'28d07ef48e40', u'373ac79f615f', u'a3ec4faddbec', u'c0195f9568c6', u'cc4ebc7b826c', u'ccdfdb826c', u'cc4fa826c', u'cc4eeesb826c', u'ccfesb826c']

fw.write(' '.join(row))

this works beacuse the join function joins everything in the list into the string

Adrian
  • 33
  • 1
  • 7
  • Hi and thanks for the answer. It would be great if you could explain to us how and why your code solves the OP's problem as code itself is not always easy to read. – Simas Joneliunas Jan 27 '22 at 06:29
0

The format string is in it's simplest form. What you can "simplify" is the conversion to string:

"%s %s <%s> [%s] %s %s (%s) %s: %s".format(map(str, row))

map(str, row) will call str() on all elements n row, and returns a list in 2.7, and iterator in 3.7.

handras
  • 1,548
  • 14
  • 28
0

Depending on your Python version, you can:

For Python 3.6 and later use new format-strings, which are the most-recommended approach:

row = [u'28d07ef48e40', u'373ac79f615f', u'a3ec4faddbec', u'c0195f9568c6', u'cc4ebc7b826c', u'ccdfdb826c', u'cc4fa826c', u'cc4eeesb826c', u'ccfesb826c']

fw.write(f'{row[0]} {row[1]} [{row[2]}] ...')

For lower versions of Python 3, you can use str.format(), which is recommended over %-formatting:

fw.write('{} {} <{}> [{}] {} {} ({}) {}: {}'.format(row[0], row[1], row[2], ...)

For Python 2 you continue with %-formatting, but you dont need to call str() on arguments - it is done automatically:

fw.write("%s %s <%s> [%s] %s %s (%s) %s: %s" % tuple(row))
grapes
  • 8,185
  • 1
  • 19
  • 31
  • 1
    You're missing an `f` in front of your Python 3.6 string. Edited for you – ycx Dec 26 '18 at 09:53
  • @ycx sorry, I occasionally have overwritten your edit and thus deprived your +2, but then upvoted one of your good answers for you to get scored – grapes Dec 26 '18 at 10:01
0

The *row operator will pack the list

kirikoumath
  • 723
  • 9
  • 20