【问题标题】:Adding quotes to an output in python在python的输出中添加引号
【发布时间】:2019-10-02 17:54:54
【问题描述】:

我正在尝试用单引号打印最终输出,但不知道该怎么做。对python有点陌生,所以任何让我走上正轨的指导都会有所帮助。

我尝试在打印函数中将引号与变量连接起来,但出现“无效语法”错误

sample = []
while True:
    print ('Enter items into this list or blank + enter to stop')
    name=input()
    if name == '':
        break
    sample = sample + [name]
print(sample)

sample.insert(len(sample)-1, 'and')
print(sample)

print('Here is the final output:')
print(*sample, sep = ", ")  

最终输出显示类似这样的内容: A、B、C、D

但是,所需的输出是: 'A,B,C,和,D'

【问题讨论】:

    标签: python-3.x variables quotes


    【解决方案1】:

    如何预先使用join 将列表加入一个字符串,然后通过string.formatf-string 在打印中使用该字符串

    print('Here is the final output:')
    print(sample)
    s = ', '.join(sample).strip()
    print(f"'{s}'")
    

    输出将是

    ['A', 'B', 'C', 'and', 'D']
    Here is the final output:
    'A, B, C, and, D'
    

    f-string 用于 python3.6

    s = ', '.join(sample).strip()
    
    print(f"'{s}'")
    

    【讨论】:

      【解决方案2】:

      转义如下引号

      print('\'hello world\'')
      

      或者使用双引号

      print("'hello world'")
      

      【讨论】:

      • 虽然这适用于简单的用例,但我不认为 OP 停留在那个级别。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多