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

試著忘記壹切 提交于 2019-12-03 06:27:29

问题


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 pretty sure you can do this in Java.


回答1:


answer = True
myvar = "the answer is " + str(answer)

Python does not do implicit casting, as implicit casting can mask critical logic errors. Just cast answer to a string itself to get its string representation ("True"), or use string formatting like so:

myvar = "the answer is %s" % answer

Note that answer must be set to True (capitalization is important).




回答2:


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



回答3:


answer = True
myvar = "the answer is " + str(answer)

or

myvar = "the answer is %s" % answer



回答4:


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.




回答5:


answer = True

myvar = 'the answer is ' + str(answer) #since answer variable is in boolean format, therefore, we have to convert boolean into string format which can be easily done using this

print(myvar)




回答6:


In the latest version of Python (3.7.0), f-strings have been introduced.

Note:

boolean = True
output = 'The answer is' + boolean

wont work, because booleans cannot be concatonated to strings.

Using an f-string, you can create a string version of the boolean and concatonate it to the output string all in one go, like this:

boolean = True
output = f'The answer is {boolean}'

To use f-strings, put the variable (of any type) in curly braces {} and put an f in front of the string (as shown above).

Note: this also works with integers and other data types that can be parsed into the print() function.



来源:https://stackoverflow.com/questions/10509803/how-do-i-concatenate-a-boolean-to-a-string-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!