How do I concatenate a boolean to a string in Python?

后端 未结 6 1432
别那么骄傲
别那么骄傲 2021-01-31 12:57

I want to accomplish the following

answer = True
myvar = \"the answer is \" + answer

and have myvar\'s value be \"the answer is True\". I\'m pr

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-31 13:40

    The recommended way is to let str.format handle the casting (docs). Methods with %s substitution may be deprecated eventually (see PEP3101).

    >>> answer = True
    >>> myvar = "the answer is {}".format(answer)
    >>> print(myvar)
    the answer is True
    

    In Python 3.6+ you may use literal string interpolation:

     >>> print(f"the answer is {answer}")
    the answer is True
    

提交回复
热议问题