【问题标题】:How to insert a variable value in a string in python如何在python中的字符串中插入变量值
【发布时间】:2017-11-11 17:34:34
【问题描述】:

这是一个简单的例子

amount1 = input("Insert your value: ")
amount2 = input("Insert your value: ")
print "Your first value is", amount1, "your second value is", amount2

这没关系,但我想知道是否有另一种方法可以将变量包含在字符串中而不使用连接或逗号。

这可能吗?

【问题讨论】:

标签: python string input


【解决方案1】:

在 Python 3.6+ (PEP498) 中,您可以使用格式化的字符串文字,也称为 f 字符串:

amount1 = input('Insert your value: ')
amount2 = input('Insert your value: ')

print(f'Your first value is {amount1}, your second value is {amount2}')

【讨论】:

    【解决方案2】:

    您也可以使用旧的 % 格式:

    print "this is a test %03d which goes on" % 10
    

    这个页面https://pyformat.info/有一个很好的比较!

    【讨论】:

      【解决方案3】:

      使用字符串格式:

      s = "Your first value is {} your second value is {}".format(amount1, amount2)
      

      这会自动处理数据类型转换,所以不需要str()。

      有关详细信息,请参阅 Python 文档:

      https://docs.python.org/3.6/library/string.html#formatstrings

      【讨论】:

      • stackoverflow.com/a/53865969/3052535 更容易阅读并且更短。
      • @Manuel 需要3.6+,复杂情况下不一定更容易阅读。这样你也可以这样做:"{arg1}".format(arg1=my_var)btw
      • 不知道 3.6 的限制。酷谢谢!给出参数名称非常好。
      猜你喜欢
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 2017-03-02
      相关资源
      最近更新 更多