英文:
How do we test if a character is usually proceeded by a backslash?
问题
When writing strings, computer programmers will often insert something called an "escape sequence."
For example, the string literal "Hello World\n"
ends in a line feed character \n
.
As another example, the string literal "Hello World\r"
ends in a carriage return character \r
.
How do we test whether or not a character is usually preceded by a back-slash character?
characters = [chr(num) for num in range(32, 127)]
for ch in characters:
if is_slashed(ch):
print(repr(ch).ljust(20), "IS SLASHED")
else:
print(repr(ch).ljust(20), "IS **NOT** SLASHED")
Suppose that ch
is a line-feed character.
Then we have:
repr(ch) ==
[single_quote, backslash_character, the_letter_n, single_quote]
After that, we have...
repr(ch)[1:-2] ==
[backslash, letter n]
Can we test repr(ch)[1:-2][0] == backslash
?
Why is there an error message in the following code?
characters = [chr(num) for num in range(32, 127)]
for ch in characters:
if not repr(ch)[1:-2][0] == "\\":
print(ch)
英文:
When writing strings, computer programmers will often insert something called an "escape sequence".
For example, the string literal "Hello World\n"
ends in a line feed character \n
.
As another example, the string literal "Hello World\r"
ends in a carriage return character \r
.
How do we test whether or not a character is usually proceeded by a back-slash character?
characters = [chr(num) for num in range(32, 127)]
for ch in characters:
if is_slashed(ch):
print(repr(ch).ljust(20), "IS SLASHED")
else:
print(repr(ch).ljust(20), "IS **NOT** SLASHED")
Suppose that ch
is a line-feed character.
Then we have:
repr(ch) ==
[single_quote, backslash_character, the_letter_n, single_quote]
After that, we have...
repr(ch)[1:-2] ==
[backslash, letter n]
Can we test repr(ch)[1:-2][0] == backslash
?
Why is there an error message in the following code?
characters = [chr(num) for num in range(32, 127)]
for ch in characters:
if not repr(ch)[1:-2][0] == "\\":
print(ch)
答案1
得分: 1
下次您发布时,您还应该发布您遇到的错误。我运行了代码,出现了一个由[1:-2]
引起的字符串索引超出范围的错误,如果您将其替换为[1]
,就像这样:
characters = [chr(num) for num in range(32, 127)]
for ch in characters:
if not repr(ch)[1] == "\\\"":
print(repr(ch))
如果您还有其他问题或需要进一步的帮助,请告诉我。
英文:
next time you post, you should also post the error you get.
I ran the code and got a string index out of range caused by the [1:-2]
which if you replace with [1]
like this
characters = [chr(num) for num in range(32, 127)]
for ch in characters:
if not repr(ch)[1][0] == "\\":
print(repr(ch))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论