Ways to concatenate boolean to string - Python
Last Updated :
12 Jul, 2025
Concatenating a boolean to a string in Python involves converting the boolean value (True or False) into a string format and then combining it with other string elements. For example, given s = "Facts are" and v = True, the expected output after concatenation is "Facts are True". Let's explore different ways to achieve this.
Using f-strings
f-strings provide a concise and efficient way to format strings using {} placeholders. They allow embedding expressions directly into string literals with an f prefix. This method is faster and more readable compared to older formatting techniques.
Python
s = "Facts are"
v = True
res = f"{s} {v}"
print(res)
Explanation: f"{s} {v}" uses an f-string to create a formatted string by embedding the values of s and v. The placeholders {s} and {v} are replaced with "Facts are" and True, respectively.
Using str()
str() function explicitly converts non-string data types, including booleans, into string format. It is commonly used with the + operator to concatenate values. This method is simple and works in all Python versions but requires explicit type conversion.
Python
s = "Facts are"
v = True
res = s + " " + str(v)
print(res)
Explanation: s + " " + str(v) concatenates the string s, a space " ", and the string representation of v using the str() function. The str(v) converts the boolean True into the string "True", ensuring proper concatenation.
The % formatting method uses format specifiers like %s (string), %d (integer), and %f (float) to insert values into a string. This method is still supported but is less flexible and readable compared to modern alternatives like f-strings or .format().
Python
v = True
res = "Facts are %s" % v
print(res)
Explanation: The %s acts as a placeholder for a string and % v replaces it with the value of v, which is True. This results in the final string "Facts are True", which is stored in res.
format() allows string formatting using {} placeholders. It provides more flexibility than % formatting by supporting positional and keyword arguments.
Python
s = "Facts are"
v = True
res = "{} {}".format(s, v)
print(res)
Explanation: format() method to insert the values of s and v into the string. The {} placeholders are replaced sequentially by s, which is "Facts are" and v, which is True.