pycharm 练习 "Character Escaping": 任务完成但语法错误

pycharm exercise "Character Escaping": task completed but wrong syntax

我正在学习 PyCharm Edu Edition 中的内置教程,但我被困在字符串 - 字符转义上。 在练习中,我被要求打印以下内容: 这个冰淇淋的名字是"Sweeet'n'Tasty" 通过使用字符转义,这是我的代码:

print("The name of this ice-cream is \"Sweeet\'n\'Tasty\"")

它仍然给我 "Sorry the wrong string is printed"。老实说,我不认为我打印了错误的字符串。有帮助吗?

您必须转义 ",因为您在打印中使用它,但您的 ' 不需要保护。

打印“\'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 行为。

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("The name of this ice-cream is \"甜蜜美味\"")

最后一个 print 语句使用单引号,所以测试希望你只转义 'n' 周围的单引号,所以这一行对我有用:

print('The name of this ice-cream is "Sweeet\'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\" 被读取为多个字符串?就像我说的,真正的初学者。 (另外,sweet 会不会写错了?)

我也遇到了同样的问题。 字符串是正确的,但它仍然说我得到了错误的字符串。然后我发现我的答案在答案占位符之外,只需重新设置任务,问题就解决了。

print('The name of this ice-cream is "Sweet\'n\'Tasty"')