如何在同一个字符串中使用单引号和双引号?

我正在一个项目中工作,其中你需要输入一句话,并且我需要能够在这句话中使用"和',例如Input ="我说,'嗨,怎么样?'"print(Input)其中我会得到一个错误。如果有人知道如何修复这个问题,那将是非常好的。

点赞
用户12918181
用户12918181

请见https://www.lua.org/pil/2.4.html。Lua有一个非常有趣的特性,用方括号来声明字符串:

input = [[I said, "Hi what's up?"]]
input = "I said, \"Hi what's up?\""
input = 'I said, "Hi what\'s up?"'
2020-02-22 22:06:18
用户9558467
用户9558467

我将在@Darius上述内容的基础上,再告诉一些事情

当您试图在字符串内添加引号时,lua解释器会感到困惑,并在下一个引号后中断您的字符串,而不是到达行尾。这是错误的原因。

尝试通过以下代码理解它

str = "Hello I"m somebody" -- here the interpreter will think str equals to "Hello I" at first, and then it will find some random characters after which may make it confused (as m somebody is neither a variable nor a keyword)"

-- you can also see the way it got confused by looking at the highlighted code

--What you can do to avoid this is escaping the quotes
str = "Hello I\"m somebody" -- here the interpreter will treat \" as a raw character (") and parse the rest.

您也可以使用转义字符()与其他字符一起使用,如 \'\"\ [\ n(换行符),\ t(制表符)等等。

2020-02-25 11:23:24