在Python中打印转义字符的方法

在Python中打印转义字符的方法

在Python中打印转义字符的方法

  转义字符是通常用于执行某些任务的字符,它们在代码中的使用指示编译器采取映射到该字符的适当操作。例子 :’\n’ –> 留下一行 ‘\t’ –> 留下一个空格,本文晓得博客为你介绍在Python中打印转义字符的方法

在Python中打印转义字符的方法
在Python中打印转义字符的方法
'\n'  -->  Leaves a line 换下一行
'\t'  -->  Leaves a space 输出一个空格
ch = "I\nLove\tpythonthree.com blog"

print ("The string after resolving escape character is : ")
print (ch)


输出:
The string after resolving escape character is
I
Love	pythonthree.com blog

  但在某些情况下,不希望解析转义,即必须打印整个未解析的字符串。这些是通过以下方式实现的。

  推荐:Python Lambda函数的10个实际用例

使用repr()

使用repr()打印转义字符
在Python中打印转义字符的方法

  该函数返回可打印格式的字符串,即不解析转义序列。 

ch = "I\nLove\txiao blog"

print ("The string without repr() is : ")
print (ch)

print ("\r")

print ("The string after using repr() is : ")
print (repr(ch))


输出:
The string without repr() is : 
I
Love	xiao blog

The string after using repr() is : 
'I\nLove\txiao blog'

  推荐:在Python中使用正则表达式验证电子邮件地址

使用“r/R”

使用r/R打印转义字符
在Python中打印转义字符的方法

  将“r”或“R”添加到目标字符串会在内部触发字符串的 repr() 并停止解析转义字符。 

ch = "I\nLove\txiao blog"

print ("The string without r / R is : ")
print (ch)

print ("\r")

# using "r" to prevent resolution
ch1 = r"I\nLove\txiao blog"

print ("The string after using r is : ")
print (ch1)

print ("\r")

# using "R" to prevent resolution
ch2 = R"I\nLove\txiao blog"

print ("The string after using R is : ")
print (ch2)

输出:
The string without r / R is : 
I
Love	xiao blog

The string after using r is : 
I\nLove\txiao blog

The string after using R is : 
I\nLove\txiao blog

  推荐:用于数据可视化5个Python包

使用原始字符串表示法

  我们还可以使用原始字符串表示法在 Python 中打印转义字符。我们只需在字符串的左引号前添加字母“r”即可。算法:

  • 使用所需的转义序列定义原始字符串变量。
  • 使用 print() 函数打印字符串。
string = "I\nLove\tGeeks\tforgeeks"
print(string)

输出:
I
Love	Geeks	forgeeks

  推荐:如何在Python中使用Unicode

  推荐:零基础如何开始学习Python

给文章评分

晓得博客,版权所有丨如未注明,均为原创
晓得博客 » 在Python中打印转义字符的方法

转载请保留链接:https://www.pythonthree.com/print-escape-characters/

Claude、Netflix、Midjourney、ChatGPT Plus、PS、Disney、Youtube、Office 365、多邻国Plus账号购买,ChatGPT API购买,优惠码XDBK,用户购买的时候输入优惠码可以打95折

Chatgpt-Plus注册购买共享账号
滚动至顶部