【问题标题】:How do I add a statement in a variable when part of the statement is variable and the variables value is too be assigned?当语句的一部分是变量并且变量值也被分配时,如何在变量中添加语句?
【发布时间】:2019-07-16 14:20:05
【问题描述】:

所以我有两个变量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 个句子,将其视为列表吗?如果是这样,当我打印带有多个句子的 a 时,我希望输出为 -

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

以此类推,直到打印完所有句子。

【问题讨论】:

    标签: python-3.x string variables


    【解决方案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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 2018-04-02
      • 2017-01-07
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      相关资源
      最近更新 更多