Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you protect yourself from missing comma in vertical string list in python?

Tags:

python

In python, it's common to have vertically-oriented lists of string. For example:

subprocess.check_output( [
  'application',
  '-first-flag',
  '-second-flag',
  '-some-additional-flag'
] )

This looks good, readable, don't violate 80-columns rule... But if comma is missed, like this:

subprocess.check_output( [
  'application',
  '-first-flag'  # missed comma here
  '-second-flag',
  '-some-additional-flag'
] )

Python will still assume this code valid by concatenating two stings :(. Is it possible to somehow safeguard yourself from such typos while still using vertically-oriented string lists and without bloating code (like enveloping each items inside str())?

like image 603
grigoryvp Avatar asked Sep 28 '12 23:09

grigoryvp


People also ask

How do you ignore a comma in a string in Python?

sub() function to erase commas from the python string. The function re. sub() is used to swap the substring. Also, it will replace any match with the other parameter, in this case, the null string, eliminating all commas from the string.

How do you put a comma in a list in Python?

How to Convert a Python List into a Comma-Separated String? You can use the . join string method to convert a list into a string. So again, the syntax is [seperator].

How do you add a comma to a string in Python?

format to add commas to a number. Use str. format(number) with "{:,}" as str to signal the use of a comma for a thousands separator and return a string with commas added to number .

How do you print a string with commas in Python?

print() comma-separated strings Python provides several methods of formatting strings in the print() function beyond string addition. print() provides using commas to combine strings for output. By comma-separating strings, print() will output each separated by a space by default.


2 Answers

You can have commas at the end of a line after whitespace, like this:

subprocess.check_output( [
   'application'           ,
   '-first-flag'           ,
   '-second-flag'          ,
   '-some-additional-flag' ,
] )

Doing it that way looks a little worse, but it is easy to spot if you have missed any arguments.

like image 58
Perkins Avatar answered Oct 09 '22 19:10

Perkins


You could wrap each string in parens:

subprocess.check_output( [
  ('application'),
  ('-first-flag'),
  ('-second-flag'),
  ('-some-additional-flag'),
] )

And btw, Python is fine with a trailing comma, so just always use a comma at the end of the line, that should also reduce errors.

like image 28
Ned Batchelder Avatar answered Oct 09 '22 19:10

Ned Batchelder