+ 17

Best way to combine strings and variables in python 🐍

What is the best way to combine strings and variables in Python? Is it print(“Your health is: “ + a) or print(“Your health is: {a} “.format(a=12) When it’s a short text is normally use the first way, but if it’s a longer text with more variables I use the second way.

22nd Apr 2018, 10:40 AM
_F1_
_F1_ - avatar
5 Answers
+ 7
If you plan on continuing with Python, this is a really good question to study into, especially when it comes to Database Management, PostgreSQL, SQLite3, etc., due to the risks involved when not taking what this question is based on into consideration. For example, notice the code below ... database = sqlite3.connect('example.db') db = database.cursor() def restricted_query(information, table): return db.execute('SELECT ' + information + ' FROM ' + table).fetchall() def admin_query(permissions, query): if permissions == 'allowed': x = db.execute(query).fetchall() database.commit() return x else: return 'Nope' Suppose that a user with limited permissions wanted to do evil things and that he could only access restricted_query(). Since the strings in the query are formatted the way they are, he could pull off a basic SQL-injection and bypass the restrictions that are set by the admin with ease.
6th May 2018, 3:39 PM
Fox
Fox - avatar
+ 6
It depends. The format method can be used if the variable is not a string(whereas in concatenation it has to be a string) and also can be used to print the variable multiple times( ex: 'he{0}{0}o'. format('l'))
22nd Apr 2018, 10:56 AM
Vivek Sivaramakrishnan
Vivek Sivaramakrishnan - avatar
+ 5
I mostly use: a = 12 print ("Your health is:", a)
22nd Apr 2018, 11:06 AM
Paul
Paul - avatar
+ 2
the second method is definitely more powerful
26th Apr 2018, 6:59 AM
Auro archit Mishra
Auro archit Mishra - avatar
+ 1
print("your health is :{a}".format(a=12) in the pest
25th Apr 2018, 5:50 PM
Wafaaabdo