【问题标题】:How can we place the value a variable in the middle of a sentence in python?我们如何在python的句子中间放置一个变量的值?
【发布时间】:2020-08-16 04:47:51
【问题描述】:

例如,我有一个整数变量usf = 5,我希望我的输出是It will be floor number 5 in US。但是当我把它写成print('It will be floor number', usf 'in US') 时,我得到了语法错误。但是当我把它写成print('US floor is', usf) 时它工作得很好。变量放在句子中间的方法是什么?

【问题讨论】:

    标签: python-3.x string variables error-handling printing


    【解决方案1】:
    print('It will be floor number', usf, 'in US')
    #                                   ^
    

    你忘了一个逗号

    虽然如果你有 Python 3.6 或更高版本,请使用f-strings

    print(f'It will be floor number {usf} in US')
    

    【讨论】:

      【解决方案2】:

      使用f-strings 使字符串格式化/插值方式更容易。

      在您的示例中,它将是 print(f"It will be floor number {usf} in US")

      而且,您的原始代码也有语法错误(很可能?),因为您忘记在 'usf' 之后使用另一个逗号来分隔最终字符串的第三部分。

      print('It will be floor number', usf 'in US')

      VS

      print('It will be floor number', usf, 'in US')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-23
        • 2013-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多