当部分语句是变量并且变量值也被赋值时,如何在变量中添加语句?

时间:2019-07-16 14:20:05

标签: python-3.x string variables

所以我有两个变量sc。两者都是一个字的字符串。 我有第三个变量a

比方说-

s=Nevad
c=Carson City

我运行的代码是-

a=(s," is the capital of ",c)

所以当我打印a时,我得到的输出是-

('Nevad', ' is the capital of ', 'Carson City')

我想要的输出是

Nevad is the capital of Carson City

另外,我可以在a中存储5个句子,将其像list一样吗?如果是这样,当我用多个句子打印a时,我希望输出为-

Nevad is the capital of Carson City
Massachusett is the capital of Boston

依次类推,直到所有句子都打印出来。

1 个答案:

答案 0 :(得分:1)

您要查找的是字符串格式化程序:

In [1]: s = "Nevada"                                                                                                                                                                                                                                                                                                          

In [2]: c = "Carson City"                                                                                                                                                                                                                                                                                                     

In [3]: a = "{} is the capital of {}".format(c, s)                                                                                                                                                                                                                                                                            

In [4]: a                                                                                                                                                                                                                                                                                                                     
Out[4]: 'Carson City is the capital of Nevada'