gpt4 book ai didi

string - 是否可以使用 "plain"长字符串?

转载 作者:行者123 更新时间:2023-12-02 17:57:41 25 4
gpt4 key购买 nike

在 Julia 中,你不能存储这样的字符串:

str = "\mwe"

因为有一个反斜杠。因此,以下内容可以帮助您防止这种情况发生:

str = "\\mwe"

"$,\n" 和许多其他符号也会发生同样的情况。我的问题是,鉴于您有一个包含数千个字符的极长字符串,即使使用搜索和替换(Ctrl + H),处理所有不同的情况也不是很方便,有没有办法将其直接分配给变量?

也许以下内容(我尝试过)可以让我了解我想要什么:

str = """\$$$ \\\nn\nn\m this is a very long and complicated (\n^$" string"""

这里"""不合适,我应该用什么代替?

最佳答案

快速回答:raw string literalsraw"\$$$\\\nn..." 会让你到达那里的大部分方式。

原始字符串文字允许您在引号之间放置您喜欢的几乎任何内容,并且 Julia 会保持键入的字符,而不会进行替换、扩展或插值。这意味着您可以轻松地完成此类操作:

a = raw"\mwe"
@assert codepoint(a[1]) == 0x5c # Unicode point for backslash

b = raw"$(a)"
@assert codepoint(b[1]) == 0x25 # Unicode point for dollar symbol

问题始终是定义字符串开始和结束位置的分隔符。你必须有某种方式告诉 Julia 字符串文字中包含什么,不包含什么,Julia 使用双引号来做到这一点,这意味着如果你想在字符串文字中使用双引号,你仍然必须转义这些:

c = raw"\"quote"  # note the backslashe
@assert codepoint(c[1]) == 0x22 # Unicode point for double quote marks

如果这让您烦恼,您可以将三引号与 raw 结合起来,但是如果您想在字符串中表示文字三引号,您仍然必须转义那些 :

d = raw""""quote"""  # the three quotes at the beginning and three at the end delimit the string, the fourth is read literally
@assert codepoint(d[1]) == 0x22 # Unicode point for double quote marks

e = raw"""\"\"\"""" # In triple quoted strings, you do not need to escape the backslash
@assert codeunits(e) == [0x22, 0x22, 0x22] # Three Unicode double quote marks

如果这让您烦恼,您可以尝试编写一个宏来避免这些限制,但您最终总是必须告诉 Julia 您想要在哪里开始处理字符串文字以及想要在哪里结束处理字符串文字,因此,您始终必须选择某种方法来将字符串文字与代码的其余部分分隔开,并在字符串中转义该分隔符。

编辑:您不需要转义原始字符串文字中的反斜杠即可在字符串中包含引号,只需转义引号即可。但是如果您想要一个反斜杠后跟一个引号,则必须将两者都转义:

f = raw"\"quote"
@assert codepoint(f[1]) == 0x22 # double quote marks

g = raw"\\\"quote" # note the three backslashes
@assert codepoint(g[1]) == 0x5c # backslash
@assert codepoint(g[2]) == 0x22 # double quote marks

如果您转义反斜杠而不是引号,Julia 会感到困惑:

h = raw"\\"quote"
# ERROR: syntax: cannot juxtapose string literal

这在the documentation中的警告中进行了解释。 .

关于string - 是否可以使用 "plain"长字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75325401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com