📜  Python|用双引号打印字符串

📅  最后修改于: 2022-05-13 01:54:50.640000             🧑  作者: Mango

Python|用双引号打印字符串

很多时候,在使用Python字符串时,我们会遇到一个问题,即我们需要在字符串中使用双引号,然后希望将其打印出来。这种问题发生在许多领域,如日常编程和网络开发领域。让我们讨论可以执行此任务的某些方式。

方法#1:使用反斜杠(“\”)
这是解决此问题的一种方法。在这种情况下,我们只是在双引号之前使用了一个反斜杠,它就被转义了。

# Python3 code to demonstrate working of 
# Printing String with double quotes
# Using backslash
  
# initializing string
# using backslash
test_str = "geeks\"for\"geeks"
  
# printing string
print("The string escaped with backslash : " + test_str)
输出 :
The string escaped with backslash : geeks"for"geeks

方法#2:使用三引号
这是Python中打印和初始化字符串的另一种方式。除了多行注释外,三引号也是转义的好方法。

# Python3 code to demonstrate working of 
# Printing String with double quotes
# Using triple quotes
  
# initializing string
# using triple quotes
test_str = """geeks"for"geeks"""
  
# printing string
print("The string escaped with triple quotes : " + test_str)
输出 :
The string escaped with triple quotes : geeks"for"geeks