如何在 python 的文本字符串中同时包含引号和双引号?

How can I include both quotes and double quotes in a text string in python?

提问人:Luca 提问时间:3/13/2022 最后编辑:ppperyLuca 更新时间:3/14/2022 访问量:65

问:

我正在尝试自动执行包含引号“ 和 ' 的 Minecraft 命令。 当我连接字符串变量时,它们会弄乱字符串开头和结尾的引号。有没有办法避免这种情况?

Name = input("User name: ")
Age = input("User age: ")
Sex = input("User gender: ")
Job = input("User job: ")
Final = '/give @s flower_banner_pattern{display:{Lore:['{"text":"Name: " + Name + ","color":"white"}','{"text":"Age: " + Age + ','color":"white"}','{"text":"Sex: " + Sex + ","color":"white"}','{"text":"Job: " + Job + ','color":"white"}']}}'
Python Minecraft 报价 双引号

评论

0赞 Abhi 3/13/2022
您可以尝试解决此问题triple quotes

答:

0赞 TheFaultInOurStars 3/13/2022 #1

同时使用 和 有时是错误的。如果您打算同时使用单引号和双引号以及多个引号,我建议您使用将主要引号和主要引号分开。以下示例可让您深入了解该指令:'"\

myString = 'there is a few quotations such as this \' and this \'. There is no need to use slash with ".'
print(myString)

输出

there is a few quotations such as this ' and this '. There is no need to use slash with ".

评论

1赞 Luca 3/13/2022
我只是尝试了一下,效果很好!谢谢你的帮助
0赞 Tomer Geva 3/13/2022 #2

我不知道Minecraft命令是如何工作的,但是如果你用一个引号开始Final变量,那么如果你想y使用一个引号,那么在字符串的中间,你应该这样做。'\'

这意味着以下操作应该有效:

Name = input("User name: ")
Age = input("User age: ")
Sex = input("User gender: ")
Job = input("User job: ")
Final = '/give @s flower_banner_pattern{display:{Lore:[\'{"text":"Name: " + Name + ","color":"white"}\',\'{"text":"Age: " + Age + \',\'color":"white"}\',\'{"text":"Sex: " + Sex + ","color":"white"}\',\'{"text":"Job: " + Job + \',\'color":"white"}\']}}'

1赞 Ncgomez17 3/13/2022 #3

要在 Python 中指示引号和双引号,您必须按以下方式指示它们:

\'-> Single quote for python string

\" -> Two quotes for python String

我刚才指出的只是将这些字符放在字符串中,它们与字符串开头和结尾的引号无关