+ 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.
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.
+ 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'))
+ 5
I mostly use:
a = 12
print ("Your health is:", a)
+ 2
the second method is definitely more powerful
+ 1
print("your health is :{a}".format(a=12) in the pest