网站首页 > 技术文章 正文
>>> 'spam eggs' # single quotes
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
在交互式解释器中,输出字符串括在引号中,特殊字符用反斜杠转义。虽然这有时看起来可能与输入不同(括起来的引号可能会更改),但这两个字符串是等效的。如果字符串包含单引号且不包含双引号,则字符串放在双引号中,否则用单引号括起来。 print()函数通过省略括起来的引号并打印转义字符和特殊字符来生成更具可读性的输出:
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a new line
First line.
Second line.
如果不希望前面的字符被解释为特殊字符,则可以通过在第一个引号前添加一个原始字符串:\r
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
字符串文本可以跨越多行。一种方法是使用三引号:或 。行尾会自动包含在字符串中,但可以通过在行尾添加 来防止这种情况发生。以下示例:"""...""" 和'''...'''
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
生成以下输出(请注意,不包括初始换行符):
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
与其他语言不同,特殊字符单引号(‘ ’)和双引号(“ ”)具有相同的含义。两者之间的唯一区别是,在单引号中,您不需要转义(如果你已经转义),反之亦然。
猜你喜欢
- 2024-12-13 Python数据类型字符串的几种表示形式
- 2024-12-13 python 基础语法详解(入门必读)
- 2024-12-13 轻松掌握!Python 基本语法与核心数据类型全解析
- 2024-12-13 Python注释方式有哪些
- 2024-12-13 Word 神器 python-docx
- 2024-12-13 万字干货,Python语法大合集,一篇文章带你入门
- 2024-12-13 Python之open()函数
- 2024-12-13 编程语言python:数据类型
- 2024-12-13 Python基础语法到高级概念
- 2024-12-13 Python字符串单引号('...')和双引号("...")的区别
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 90℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)