如何测试一个字符是否通常在其前面有一个反斜杠?

huangapple go评论63阅读模式
英文:

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))

huangapple
  • 本文由 发表于 2023年2月24日 06:03:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定