我正在按照PyCharm Edu Edition中的内置教程进行操作,并且我遇到了Strings - Character Escaping。在练习中,我被要求打印以下内容:这个冰淇淋的名称是“Sweeet'n'Tasty”,使用字符转义,这是我的代码:
print("The name of this ice-cream is \"Sweeet\'n\'Tasty\"")
它仍然给我“抱歉打印错误的字符串”。老实说,我认为我没有打错字符串。有帮助吗?
你必须逃避“因为你在打印中使用它,但你的'不需要保护。
打印“\'n”和“'n”将输出相同的行,但即使不可见,转义也会生成运动控制器读取的内容。
尝试删除\之前\
print("The name of this ice-cream is \"Sweeet'n'Tasty\"")
包含“或”的字符串的另一种解决方案是使用三元组,如下所示:
print("""The name of this ice-cream is "Sweeet'n'Tasty\"""")
在这种情况下,句子被“再次保护它的力量终止,但中间”的句子不需要受到保护。
您也可以反转使用'和'来保护'或'
print('The name of this ice-cream is "Sweeet\'n\'Tasty"')
也可以使用3':
print('''The name of this ice-cream is "Sweeet'n'Tasty"''')
如果仍然不起作用,你能提供断言测试吗?
编辑:
这似乎是你面临的问题:http://iswwwup.com/t/d08b1b05234e/print-out-text-using-one-string-in-python.html
来自模糊的测试要求/ IDE行为。
最后一个print语句使用单引号,所以测试要求你只能转义围绕'n'的单引号,所以这行对我有用:
print('The name of this ice-cream is "Sweeet\'n\'Tasty"')
dont_worry = "Don't worry about apostrophes"
print(dont_worry)
print("The name of this ice-cream is \"Sweeet\"")
print("The name of this ice-cream is \"Sweeet'n'Tasty\"")
print(“这个冰淇淋的名字是”Sweet n Tasty“”)
如果使用双引号(根据文本文件),只能解决此问题无论如何,如果您尝试此操作,它将帮助您成功完成:
print("\'The name of this ice-cream is \"Sweeet'n'Tasty\" \'")
这些课程中的说明根本不清楚,来自jetbrains的人应该研究这个。即使他们没有在说明中提到它,他们也希望你编辑第三行:
print("The name of this ice-cream is \"Sweeet\"")
对此:
print("The name of this ice-cream is \"Sweeet'n'Tasty\"")
无需在第四行中删除双引号:
print('The name of this ice-cream is "Sweeet\'n\'Tasty"')
所以完整的代码应该是这样的
dont_worry = "Don't worry about apostrophes"
print(dont_worry)
print("The name of this ice-cream is \"Sweeet'n'Tasty\"")
print('The name of this ice-cream is "Sweeet\'n\'Tasty"')
此外,这对我有用:print("The name of this ice-cream is \"Sweet'n'Tasty\"")
我是编码(任何类型)的新手,所以这只是一个猜测 - 解决方案要求你只打印一个字符串,所以也许\"Sweet\'n\'Tasty\"
被读作多个字符串?就像我说的,真正的初学者。 (也可能是那个甜言蜜语错了吗?)
我也有同样的问题。字符串是正确的,但它仍然说我得到了错误的字符串。然后我发现我的答案在答案占位符之外,只是重置任务,问题就解决了。
print('The name of this ice-cream is "Sweet\'n\'Tasty"')