simplify python print - python

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?

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

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))

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.

The *row operator will pack the list

Related

How to use column name dynamically inside insert query in djnago

cursor.execute("insert into demoapp_site ('name','firstname','lastname') values (%s,%s,%s)",site_data)
in above query I want to pass column name dynamically and %s which is inside values also not predefine that how many times it need to write
so, how can I write my sql query according to my data which comes from html table in 2d array from??
We need to build the query before using it. As follows
field_string = ""
value_string = ""
# This will string in this format "'field1','field2'"
# Assuming array is in format [["field1", "value1"],..]
# Update the for loop statement based on your input, other lines remain same
for field, value in my_field_array:
temp_field_string = "'%s'" % field
field_string = field_string + temp_field_string + ","
temp_value_string = "'%s'" % value
value_string = value_string + temp_value_string + ","
# Removing trailing comma's before passing the values
cmd = "insert into demoapp_site (%s) values (%s)" % (field_string[:-1], value_string[:-1])
cursor.execute(cmd)

Python Triple-quoted strings with variable

Trying to write to a file with variables, but that is returning error:
template = """1st header line
second header line
There are people in rooms
and the %s
"""
with open('test','w') as myfile:
myfile.write(template.format()) % (variable)
The .format method expects you to template the blanks to be filled in your string with the {}-style, not %s. It also expects the interpolated values to be given as its arguments.
template = """1st header line
second header line
There are people in rooms
and the {}
"""
myfile.write(template.format(variable))
The given string literal is printf-style string. Use str % arg:
with open('test', 'w') as myfile:
myfile.write(template % variable)
To use str.format, you should use placeholder {} or {0} instead of %s.
The Error
myfile.write(template.format()) returns nothing to which you are using % operator to concatenate
Minimal Edit
You can perfectly use %s .The problem is you mismatched parenthesis and the parenthesis i.e. ) should be after your variable as in myfile.write(template.format() % (variable)). But as template.format() is redundant, it can be ignored. Thus the correct way is
myfile.write(template % (variable))
Note:- Any string with an empty format() and no {} in the string returns the string itself

How to insert string into mysql using python correctly?

I'm quite new to python and mysql.
When I try to insert some records with fields of string, I failed to insert them into mysql because it always report error like: ProgrammingError: (1064, 'You have an error in your SQL syntax.
I am quite confused.
Occasionlly, I find it works by add additional "" to the string field, like the following:
history_market_table_name = 'my_test'
f = ['field_a', 'field_b', 'field_c', 'field_d']
r = ['a', 'b', 'c', 'd']
my_time = "'" + str(datetime.now()) + "'"
target_sql = "insert into %s (time, %s, %s, %s, %s) values(%s, %s, %s, %s, %s)" % (
history_market_table_name, f[0], f[1], f[2], f[3], my_time, repr(r[0]), repr(r[1]), repr(r[2]), repr(r[3]))
Sorry the codes are quite tedious.
Moreover, there must be something wrong with my method -- it couldn't be so stupid to insert fields with string type!
Look at the my_time variable, how ridiculous.
Any one please explain how to correctly insert string into mysql with python.
I am quit new.
So please give a correct answer and detailed explaination is highly appreciated.
Change your format string to
"insert into %s (time, %s, %s, %s, %s) values(%s, '%s', '%s', '%s', '%s')"
I.e, single quotes around the otherwise-unquoted string values you're inserting -- and lose the repr calls after the %. This will still fail if you're inserting a string value which contains a ' character... there are better ways but they don't let you parameterize the table name and field names (which is a truly peculiar requirement...), only the values.
Added: as the OP requires "a direct expression for the 'target_sql' variable", here it is:
fmt_str = "insert into %s (time, %s, %s, %s, %s) values(%s, '%s', '%s', '%s', '%s')"
target_sql = fmt_str % (history_market_table_name, f[0], f[1], f[2], f[3],
my_time, r[0], r[1], r[2], r[3])
I think it's more readable split up this way. As for "some documents for such things" which the OP also requires, MySQL has such documents with every version (and the OP didn't mention which version he or she uses) and so does Python (ditto, ditto).
The "better way" (which however don't allow parameterizing table and field names) involve using "placeholders" in lieu of value in the SQL string, rather than string substitution.
Here,
sql = "insert into my_test (time, field_a, field_b, field_c, field_d) values(%s, %s, %s, %s, %s)'
(with hard-coded, not parameterized, table and field names), and later, for a given cursor opened on the MySql DB,
cursor.execute(sql, (
str(datetime.now()), r[0], r[1], r[2], r[3]))
with no worries about quoting nor about any potential for a "sql injection" attack.

Python Not Web Linking Entire variable in str.ljust

I have Python code that pulls info from a sqlite database and then write to a html file. I'm trying to write as preformatted text and the code below places the text in columns like I am try to accomplish, but (obviously) the link is the entire length of the string, including the whitespace to the right from the .ljust.
How can I get it to only link the text of item.title instead of the entire string, plus whitespace?
content += '%s %s' % (item.slug, str(item.title).ljust(25), item.date.ljust(10)
Edit
title = str(item.title)
spaces = ' '*(25-len(title)) if len(title) <= 25 else ''
'%s%s %s' % (item.slug, title, spaces, item.date.ljust(10))
If you must do it on one line, the following should work for you:
content += '%s %s %s' % tuple(itertools.chain((item.slug,),
str(item.title).ljust(25).split(" ", 1), (item.date.ljust(10),)))
However the following should be a little easier to read
values = [item.slug]
values += str(item.title).ljust(25).split(" ", 1)
values.append(item.date.ljust(10))
content += '%s %s %s' % values
Notice I've added one extra space to your formatting string to make up for the one lost to the string split operation.
EDIT: The above code fails when item.title is greater than 25 characters. A revised version is below.
title, spaces = (str(item.title).ljust(25)+" ").split(" ", 1)
content += '%s%s %s' % (item.slug, title,
spaces, item.date.ljust(10))
This version adds a space to the end of the justified title, so the split operation is guaranteed to return a tuple of length 2.

python: join print with previous printed line

In python (2.6) is it possilbe to "join" print output with the previous line of print output? The trailing comma syntax ( print x,) doesn't work because most of the output should have a new line.
for fc in fcs:
count = getCount(fc)
print '%s records in %s' % ('{0:>9}'.format(count),fc)
if count[0] == '0':
delete(fc)
print '==> %s removed' % (fc)
current console output:
3875 records in Aaa
3875 records in Bbb
0 records in Ccc
==> Ccc removed
68675 records in Ddd
desired result:
3875 records in Aaa
3875 records in Bbb
0 records in Ccc ==> Ccc removed
68675 records in Ddd
import sys
sys.stdout.write("hello world")
print writes to the apps standard out and adds a newline.
However you sys.stdout is already a file object pointing to the same location and the write() function of a file object doesn't automatically append a newline to the output string so it should be exactly what you want.
You're asking if a print statement can remove the newline from the end of the previous line. The answer is no.
But you can write:
if count[0] == '0':
removed = ' ==> %s removed' % (fc)
else:
removed = ''
print '%s records in %s%s' % ('{0:>9}'.format(count), fc, removed)
The following should work:
for fc in fcs:
count = getCount(fc)
print '%s records in %s' % ('{0:>9}'.format(count),fc),
if count[0] == '0':
delete(fc)
print '==> %s removed' % (fc)
else:
print ''
There isn't a very good way to shorten that an maintain readability with the delete() in there.
While Python 2 doesn’t have the feature you look for, Python 3 has.
so you can do
from __future__ import print_function
special_ending = '==> %s removed\n' % (fc)
ending = special_ending if special_case else "\n"
print('%s records in %s' % ('{0:>9}'.format(count),fc), end=ending)

Categories