【问题标题】:Python format string containing \n and \t包含 \n 和 \t 的 Python 格式字符串
【发布时间】:2021-06-17 12:48:07
【问题描述】:

下面是我需要格式化的字符串内容:

输入:

input = 'This is line_number_1 \n \t This is second line with a tab \n \t\t This is third line with two tabs'

print(input) #This results like below,

'This is line_number_1 \n \t This is second line with a tab \n \t\t This is third line with two tabs'

但预期的输出:

'This is line_number_1 
    This is second line with a tab 
        This is third line with two tabs'

预期应该是一个字符串,而不是使用 Python 的行列表

【问题讨论】:

  • 您的问题是什么?如果您打印输入,您将获得输出。
  • 当我将它存储在一个字符串中时,我仍然可以看到 \n 和 \t
  • input 是内置函数,请勿用作名称。同样,当您 print(input) 时,它将产生所需的输出,而不是您显示的内容

标签: python python-3.x string replace line


【解决方案1】:

你混淆了输出表示的概念。如果要查看输出,则需要输出数据,即使用print() 调用。像这样:

>>> s = 'This is line_number_1 \n \t This is second line with a tab \n \t\t This is third line with two tabs'
>>> print(s)
This is line_number_1 
     This is second line with a tab 
         This is third line with two tabs

如果您只是评估s,您将看到 Python 的默认内部表示,这与您的输入相同:

>>> s
'This is line_number_1 \n \t This is second line with a tab \n \t\t This is third line with two tabs'

【讨论】:

  • 你在混淆表示。与在解释器提示符下键入 s 相比,Python 的字符串内部表示更接近于您使用 print 看到的内容。在解释器提示符下键入 s 会在字符串上调用 repr,并在字符串上调用 repr 会构建一个新字符串,该字符串表示 Python 源代码,该字符串将评估为原始字符串。换句话说,它是字符串的源代码表示,而不是 Python 的内部表示。
  • @user2357112supportsMonica 我故意使用“Python 的内部表示”而不是 repr(),因为很明显 OP 不会理解这一点。当初学者想要“摆脱我的字符串中的反斜杠”或“删除我的输出中多余的Decimal()”时,这是一个非常有用的短语。有时,用初学者会理解的术语来解释事情比严格准确更重要。将其视为“Python 代码内部”而不是“底层 CPython 解释器内部”。
【解决方案2】:

您可以直接使用 print 语句从输入中删除转义序列

input = 'This is line_number_1 \n \t This is second line with a tab \n \t\t This is third line with two tabs'
print(input)

但是,如果您希望在打印输入后出现引号,请添加额外的转义序列,如下所示:

input = '\'This is line_number_1 \n \t This is second line with a tab \n \t\t This is third line with two tabs\''
print(input)

【讨论】:

    【解决方案3】:

    不要放单斜线,而是放双斜线。喜欢:

    input = 'This is line_number_1 \\n \\t This is second line with a tab \\n \\t\\t This is third line with two tabs'
    print(input)
    

    如果你运行这段代码,你会得到如下输出:

    This is line_number_1 \n \t This is second line with a tab \n \t\t This is third line with two tabs
    

    但如果你想要制表符,那么只写 1 个斜线。

    【讨论】:

      猜你喜欢
      • 2012-10-24
      • 2018-10-18
      • 2021-12-26
      • 2023-03-06
      • 2015-03-26
      • 2017-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多