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

后端 未结 6 1303
别那么骄傲
别那么骄傲 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:47

    Using the so called f strings:

    answer = True
    myvar = f"the answer is {answer}"
    

    Then if I do

    print(myvar)
    

    I will get:

    the answer is True
    

    I like f strings because one does not have to worry about the order in which the variables will appear in the printed text, which helps in case one has multiple variables to be printed as strings.

提交回复
热议问题