Python supports C-style string formatting to create formatted Python strings. This formatting is achieved using a “%” operator. A format string consists of normal string elements along with special formatting symbols. In this topic, we will be discussing the Python %s operator.
Also known as String interpolation, String formatting is a method of formatting string-type elements. In this process, a custom string or variable is inserted into the predefined text. String formatting Python can be achieved in Python through various methods.
Basic String Formatting Using Python %s
Refer to the following implementation. We are demonstrating C-style string formatting using the %s operator. The %s operator lets you add a value to a Python string
myString = "PythonPool"
print("Welcome to, %s!" %myString)
Welcome to, PythonPool!
Python %s vs Python .format()
| %s | .format() |
|---|---|
| %s is an operator | It is a method of the in-built string class of Python. |
| It is derived from the C style formatting technique. | It was introduced in Python 3 and was made available in Python 2.7 |
| The %s operator is slightly faster than the latter since it is a syntactical notation. | It is slower due to the fact that it involves an extra method call. |
Differences Between Other Format Operators
%s vs %d
%s | %d |
|---|---|
| Derived from C | Also derived from C |
| Allows you to format strings using other string types only. | Allows you to format strings using integer types only. |
| Will maintain string format | Will truncate to an integer or a Python double. |
Recommended Reading | Demystifying the Secrets of Python %d
%s vs. %r
| %s | %r |
|---|---|
Converts the string object using str() method. | Converts the string object using repr() method. |
| Used as a regular string format specifier. | Recommended using for debugging as it’s a “raw” format specifier. |
%s vs. %f
| %s | %f |
|---|---|
| Allows you to format string constants using other string types | Allows you to format float values |
| This is derived from C and is present in Python as well | %f format specifier is a C language feature. |
Formatting Python Strings using Tuples
In order to insert multiple string types, we can make use of a Python tuple and the %s operator.
Check out the following implementation:
print('%s %s %s'%('Welcome','to','PythonPool'))
Output
Welcome to PythonPool
a = "Welcome"
b = "to"
c = "PythonPool"
print('%s %s %s'%(a,b,c))
Output
Welcome to PythonPool
Using the %s operator in a Python SQL statement
Let’s take the following example:
cursor.execute("INSERT INTO myTable VALUES (%s, %s, %s)", (a,b,c))
The escaping and quoting for the variables are done by the Python Database API. Although, using the %s string formatting variables can leave the database vulnerable and be subjected to SQL injection attacks.
Formatting Python Strings using Dictionaries
Similar to tuples, we can use a dictionary in order to format a string with multiple string types.
print('%(Website)s has over %(number)s published articles!'%{"Website": "PythonPool.com", "number": 500})
# Make sure to format the dictionary values as string
Output
PythonPool.com has over 500 published articles!
You also pass variables to the dictionaries like so:
amount = 500
website = "PythonPool.com"
print('%(Website)s has over %(number)s published articles!'%{"Website": website, "number": amount})
Output
PythonPool.com has over 500 published articles!
Using String Interpolation or f-strings to Format Strings
String interpolation was introduced recently in Python 3.6. F-strings are nothing but formatted string literals. This method allows you to embed expressions in Python string constants.
Refer to the following example:
website = "PythonPool"
f'Welcome to {website}!'
Output
Welcome to PythonPool!
“f” is a pre-fix for the string constant, thereby called f-strings. This new method of string formatting is powerful as it allows you to perform arithmetics.
num1 = 6
num2 = 6
f'The sum is {num1 + num2} and the product is {num1*num2}'
Output
The sum is 12 and the product is 36
Using the Python String Module to Format Strings
The string module is a part of the Python Standard Library under the Text Processing Services category.
The template function allows us to achieve this. Although this is a less powerful method, it’s useful in certain instances.
from string import Template
myWebsite = "PythonPool"
myTemplate = Template('Welcome to $website!')
myTemplate.substitute(website=myWebsite)
Output
Welcome to PythonPool!
Note that template strings do not support format specifiers. Use .substitute().
It is possible to use dictionaries in template strings to pass string objects.
from string import Template
myWebsite = "PythonPool"
myAmount = 500
myTemplate = Template('Welcome to $website! We have over $amount articles')
myTemplate.substitute({"website": myWebsite, "amount":myAmount})
Output
Welcome to PythonPool! We have over 500 articles
FAQs
The %s operator will not work if you insert it in a regular expression. However, there is an expression that mimics the properties of %s. That is – \S+
Conclusion
We have looked at the C-derived %s string format specifier. Other methods to format Python string constants have been discussed as well. The differences between %s and other format specifiers have been established.
![[Fixed] typeerror can’t compare datetime.datetime to datetime.date](https://www.pythonpool.com/wp-content/uploads/2024/01/typeerror-cant-compare-datetime.datetime-to-datetime.date_-300x157.webp)
![[Fixed] nameerror: name Unicode is not defined](https://www.pythonpool.com/wp-content/uploads/2024/01/Fixed-nameerror-name-Unicode-is-not-defined-300x157.webp)
![[Solved] runtimeerror: cuda error: invalid device ordinal](https://www.pythonpool.com/wp-content/uploads/2024/01/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp)
![[Fixed] typeerror: type numpy.ndarray doesn’t define __round__ method](https://www.pythonpool.com/wp-content/uploads/2024/01/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-300x157.webp)