python 中的引号和字符串

发布于 2024-09-18 05:14:53 字数 170 浏览 4 评论 0原文

我对 python 有点陌生,但我已经编写了许多程序,包括一些需要大量字符串操作的程序,例如下载管理器、游戏和文本编辑器。
为了表示字符串文字,我使用单引号或双引号......以当时首先想到的为准。

虽然我还没有遇到任何麻烦。我的问题:Python 允许两者都有什么目的,还是只是为了兼容性、可用性等?

I'm kinda' new to python, but I have already written many programs including some like download-managers, games and text-editors which require a lot of string manipulation.
For representing a string literal I use either single or double inverted commas.. whichever comes to my mind first at that time.

Although I haven't yet faced any trouble. My question: is there any purpose for which python allows both or is it just for compatibility, usability etc?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

所谓喜欢 2024-09-25 05:14:53

Python 中的 "string"'string' 之间没有区别,因此,正如您所建议的,这只是为了可用性。

>>> 'string' == "string"
True

您还可以对多行​​字符串使用三引号:

>>> mystring = """Hello
... World!"""
>>> mystring
'Hello\nWorld!'

另一个技巧是相邻的字符串文字会自动连接:

>>> mystring = "Hello" 'World!'
>>> mystring
'HelloWorld!'

还有 您可以在文档中阅读的字符串前缀

There is no difference between "string" and 'string' in Python, so, as you suggest, it's just for usability.

>>> 'string' == "string"
True

You can also use triple quotes for multiline strings:

>>> mystring = """Hello
... World!"""
>>> mystring
'Hello\nWorld!'

Another trick is that adjacent string literals are automatically concatenated:

>>> mystring = "Hello" 'World!'
>>> mystring
'HelloWorld!'

There are also string prefixes which you can read about in the documentation.

吻安 2024-09-25 05:14:53

这意味着您可以轻松地拥有一个带有任一单引号或双引号的字符串,而无需任何转义字符。所以你可以这样做:

a = 'The knights who say "ni!"'
b = "We're knights of the Round Table, we dance whene'er we're able."

It means you can easily have a string with either single or double quotes in it without needing any escape characters. So you can do:

a = 'The knights who say "ni!"'
b = "We're knights of the Round Table, we dance whene'er we're able."
野鹿林 2024-09-25 05:14:53

只是为了兼容性和可用性。

当您将其中一个嵌入到字符串中时,有时它会很有用,因此我会使用 "Who's there?"'He said: "Hello"' 相比。

另一个选项当然是三重引号字符串,就像

"""This is a long string that can contain single quotations like ' or ".
It can also span multiple lines"""

等于

'''This is a long string that can contain single quotations like ' or ".
It can also span multiple lines'''

Just for compatibility and usability.

It is sometimes useful when you have one of them embedded in the string, so I would use "Who's there?" compared to 'He says: "Hello"'.

The other option is of course triple quoted strings, like

"""This is a long string that can contain single quotations like ' or ".
It can also span multiple lines"""

which is equal to

'''This is a long string that can contain single quotations like ' or ".
It can also span multiple lines'''
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文