包含\n和\t的Python格式字符串

包含\n和\t的Python格式字符串,python,python-3.x,string,replace,line,Python,Python 3.x,String,Replace,Line,下面是我需要格式化的字符串内容: 输入: 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 th

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

输入:

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时,所需的应该是字符串,而不是行列表。您混淆了输出和表示的概念。如果要查看输出,则需要输出数据,即使用打印调用。像这样:

>>> 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'

不要放一条斜线,而是放两条斜线。比如:

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个斜杠进行写入。

您可以直接使用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)

你的问题是什么?如果您打印输入,您将获得输出。当我将其存储在字符串中时,我仍然可以看到\n和\t输入是一个内置函数,不要用作名称。同样,当您打印输入时,它将生成所需的输出,而不是您所显示的内容—您正在混合表示。Python对字符串的内部表示比在解释器提示下键入s更接近您在print中看到的内容。在解释器提示下键入s将调用字符串上的repr,在字符串上调用repr将生成一个新字符串,表示将计算为原始字符串的Python源代码。换句话说,它是字符串的源代码表示形式,而不是Python的内部表示形式。@user2357112supportsMonica我故意使用Python的内部表示形式而不是repr,因为OP显然不理解这一点。当初学者想要去掉字符串中的反斜杠或删除输出中多余的小数点时,这是一个非常有用的短语。有时,用初学者能理解的术语解释事情比严格准确更重要。将其视为Python代码的内部,而不是底层CPython解释器的内部。