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.
并且myvar的值是“答案是真的”。我很确定你可以用Java做到这一点。
4 个解决方案
#1
88
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:
Python不进行隐式转换,因为隐式转换可以掩盖关键的逻辑错误。只需将答案转换为字符串本身以获取其字符串表示形式(“True”),或使用字符串格式,如下所示:
myvar = "the answer is %s" % answer
Note that answer must be set to True
(capitalization is important).
请注意,答案必须设置为True(大小写很重要)。
#2
#3
7
answer = True
myvar = "the answer is " + str(answer)
or
要么
myvar = "the answer is %s" % answer
#4
1
Using the so called f strings:
使用所谓的f字符串:
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.
我喜欢f字符串,因为人们不必担心变量在打印文本中出现的顺序,这有助于将多个变量打印为字符串。
#1
88
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:
Python不进行隐式转换,因为隐式转换可以掩盖关键的逻辑错误。只需将答案转换为字符串本身以获取其字符串表示形式(“True”),或使用字符串格式,如下所示:
myvar = "the answer is %s" % answer
Note that answer must be set to True
(capitalization is important).
请注意,答案必须设置为True(大小写很重要)。
#2
9
The recommended way is to let str.format
handle the casting (docs). Methods with %s
substitution may be deprecated eventually (see PEP3101).
建议的方法是让str.format处理转换(docs)。 %s替换的方法最终可能会被弃用(参见PEP3101)。
>>> answer = True
>>> myvar = "the answer is {}".format(answer)
>>> print myvar
the answer is True
#3
7
answer = True
myvar = "the answer is " + str(answer)
or
要么
myvar = "the answer is %s" % answer
#4
1
Using the so called f strings:
使用所谓的f字符串:
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.
我喜欢f字符串,因为人们不必担心变量在打印文本中出现的顺序,这有助于将多个变量打印为字符串。