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()
)?
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 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].
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With