如何拆分包含特殊字符的字符串

时间:2021-04-13 06:38:53

标签: python string split special-characters

string_1 = "\tVH VH VH VL N N N N N N N\n"

在这里,当我尝试使用 \t 函数拆分字符串时,我试图拆分其中包含 \nsplit 的字符串,如下所示:

sep_setring = string_1.split()

输出:

['VH', 'VH', 'VH', 'VL', 'N', 'N', 'N', 'N', 'N', 'N', 'N']

但是,我需要一个输出如下:

['\t', 'VH', 'VH', 'VH', 'VL', 'N', 'N', 'N', 'N', 'N', 'N', 'N', '\n']

2 个答案:

答案 0 :(得分:3)

使用 re.findall

string_1 = "\tVH VH VH VL N N N N N N N\n"
matches = re.findall(r'\S+|[^\S ]+', string_1)
print(matches)

打印:

['\t', 'VH', 'VH', 'VH', 'VL', 'N', 'N', 'N', 'N', 'N', 'N', 'N', '\n']

这里是正则表达式模式的解释,它交替地找到一组非空白字符或一组空白字符(空格除外):

\S+      match one or more non whitespace characters
|        OR
[^\S ]+  match one or more whitespace characters excluding space itself

答案 1 :(得分:1)

您可以使用环视进行拆分:

(?<=\t)|(?=\n)| 
  • (?<=\t) 断言左侧的标签
  • |
  • (?=\n) 断言向右换行
  • |
  • 匹配一个空格

示例

import re
string_1 = "\tVH VH VH VL N N N N N N N\n"
sep_setring = re.split(r"(?<=\t)|(?=\n)| ", string_1)
print(sep_setring)

输出

['\t', 'VH', 'VH', 'VH', 'VL', 'N', 'N', 'N', 'N', 'N', 'N', 'N', '\n']