+ 1

What does the % sign do in python

I understand that if you say something like this print(26%5) the output would be 1 because it does the remainder. But all too often I see it used for something else and I'm clueless as of what it means. Like people use it like this sometimes print(%s + "Something else") I don't even know if the syntax was correct there.

3rd Nov 2017, 1:23 AM
Darth Vador
Darth Vador - avatar
2 Respuestas
+ 3
In string context, that's not the same operator than in number context... In string context, it's the (old) format operator, used to set placeholder: "i am %s and i am %d years old" % ( name, age ) '%' is required IN string to define placeholders, AND AFTER string, as separator of tupple with the values (usually variables) to format inside the string... The new Python3 way (even if the old is still supported) is rather: "i am {} and i am {} years old".format( name, age ) https://pyformat.info
3rd Nov 2017, 6:44 AM
visph
visph - avatar
+ 1
hum in strings it is used for string firmatting after c style like "i am %s and i am %d years old", name, age %s for strings %d for digits
3rd Nov 2017, 1:43 AM
Abdur-Rahmaan Janhangeer
Abdur-Rahmaan Janhangeer - avatar