Saturday, May 18, 2024
HomePythonConcatenate a Boolean to a String in Python? – Finxter

Concatenate a Boolean to a String in Python? – Finxter


Straightforward Answer

Use the addition + operator and the built-in str() operate to concatenate a boolean to a string in Python. For instance, the expression 'Be ' + str(True) yields 'Be True'.

s="Be " + str(True)
print(s)
# Be True
  • The built-in str(boolean) operate name converts the boolean to a string.
  • The string concatenation + operator creates a brand new string by appending the “Boolean” string to a different string.

What Can Go Incorrect With out Conversion

In case you attempt to concatenate the Boolean to a string with out conversion utilizing str(), Python will detect that you simply’re utilizing the addition + operator with incompatible operand sorts and it raises a TypeError: can solely concatenate str (not "bool") to str. Repair it by changing the Boolean to a string utilizing str().

Right here’s the concatenation gone dangerous:

s="Be " + True

The ensuing error message:

Traceback (most up-to-date name final):
  File "C:UsersxcentDesktopcode.py", line 1, in <module>
    s="Be " + True
TypeError: can solely concatenate str (not "bool") to str

And right here’s how one can resolve this rapidly and simply (as already proven):

s="Be " + str(True)
print(s)
# Be True

Various: print()

You may go a number of differing types into the print() operate, comma-separated. Python implicitly converts all values to strings and prints them to the shell. In lots of circumstances, it is a way more elegant resolution than explicitly utilizing the string concatenation operator.

Right here’s a straightforward instance:

print('Be', True)
# Be True

The print() operate additionally has some ways to customise the separator and finish strings.

👉 Really useful Tutorial: Understanding Python print()

Thanks for studying by means of the tutorial with us. ❤️ Love having you right here!


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments