2022年 12月 19日

python字符串转义序列_Python | 忽略字符串中的转义序列

python字符串转义序列

First see, how escape sequence works?

首先看,转义序列如何工作?

In the below example, we are using some of the escape sequence and their outputs, we are printing single quote (\’), double quotes (\”), printing path (double slash) (\\) and using hexadecimal values (\x).

在下面的示例中,我们使用一些转义序列及其输出,我们将打印单引号( \’ ),双引号( \“ ),打印路径(双斜杠)( \\ )并使用十六进制值( \ x )。

Program:

程序:

  1. #printing single quote
  2. str1 = "Hi, I\'m IncludeHelp"
  3. #printing double quotes
  4. str2 = "\"Hello world\""
  5. #printing path
  6. str3 = "D:\\work_folder\\python_works"
  7. #using hexadecimal values
  8. str4 = "This is \x49\x6E\x63\x6C\x75\x64\x65\x48\x65\x6C\x70"
  9. print(str1);
  10. print(str2);
  11. print(str3);
  12. print(str4);

Output

输出量

  1. Hi, I'm IncludeHelp
  2. "Hello world"
  3. D:\work_folder\python_works
  4. This is IncludeHelp

忽略转义序列 (Ignoring Escape Sequences)

To ignoring escape sequences in the string, we make the string as “raw string” by placing “r” before the string. “raw string” prints as it assigned to the string.

为了忽略字符串中的转义序列 ,我们通过在字符串前面放置“ r” ,使字符串成为“原始字符串”“原始字符串”将按分配给该字符串的方式打印。

Program:

程序:

  1. #ignoring escape sequences
  2. #ignoring single quote escape sequences
  3. str1 = r"Hi, I\'m IncludeHelp"
  4. #ignoring double quotes escape sequences
  5. str2 = r"\"Hello world\""
  6. #ignoring path escape sequences
  7. str3 = r"D:\\work_folder\\python_works"
  8. #ignoring hexadecimal values escape sequences
  9. str4 = r"This is \x49\x6E\x63\x6C\x75\x64\x65\x48\x65\x6C\x70"
  10. print(str1);
  11. print(str2);
  12. print(str3);
  13. print(str4);

Output

输出量

  1. Hi, I\'m IncludeHelp
  2. \"Hello world\"
  3. D:\\work_folder\\python_works
  4. This is \x49\x6E\x63\x6C\x75\x64\x65\x48\x65\x6C\x70

Other python string programs…

其他python字符串程序…

  • Python | Declare, assign and print the string (Different ways).

    Python | 声明,分配和打印字符串(不同方式)。

  • Python | Access and print characters from the string.

    Python | 访问和打印字符串中的字符。

  • Python | Program to print words with their length of a string.

    Python | 程序打印带有字符串长度的单词。

  • Python | Print EVEN length words.

    Python | 打印偶数个长度的单词。

  • Python | Count vowels in a string.

    Python | 计算字符串中的元音。

  • Python | Passing string value to the function.

    Python | 将字符串值传递给函数。

  • Python | Create multiple copies of a string by using multiplication operator.

    Python | 使用乘法运算符创建一个字符串的多个副本。

  • Python | Appending text at the end of the string using += Operator.

    Python | 使用+ =运算符在字符串末尾附加文本。

  • Python | Concatenate two strings and assign in another string by using + operator.

    Python | 连接两个字符串,并使用+运算符分配另一个字符串。

  • Python | Check if a substring presents in a string using ‘in’ operator

    Python | 使用’in’运算符检查字符串中是否存在子字符串

翻译自: https://www.includehelp.com/python/ignoring-escape-sequences-in-the-string.aspx

python字符串转义序列