字符串的特定分割

时间:2020-01-24 17:53:43

标签: python string split

我有这个字符串:

youtube.com.    3599    IN  TXT "google-site-verification=OQz60vR-YapmaVrafWCALpPyA8eKJKssRhfIrzM-DJI"
youtube.com.    3599    IN  TXT "v=spf1 include:google.com mx -all"
youtube.com.    3599    IN  TXT "facebook-domain-verification=64jdes7le4h7e7lfpi22rijygx58j1"

并希望将此拆分版本作为列表列出来:

[youtube.com.,3599,IN,TXT,"google-site-verification=OQz60vR-YapmaVrafWCALpPyA8eKJKssRhfIrzM-DJI",youtube.com.,3599,IN,TXT,"v=spf1 include:google.com mx -all",youtube.com.,3599,IN,TXT,"facebook-domain-verification=64jdes7le4h7e7lfpi22rijygx58j1"]

使用split()函数来将其字符串拆分为由空格分隔的每个字符串,但我想将每一行拆分为5个字符串,并由一行中的前4个空格分隔。 那怎么可能? (最好不要使用太多代码)

先谢谢您, 问候

2 个答案:

答案 0 :(得分:1)

您可以使用maxsplit

定义最大拆分数
my_string.split(maxsplit=4)

如果指定了maxsplit,则最多会发生最大拆分次数,并将字符串的其余部分作为列表的最后一个元素返回(因此,列表中最多包含maxsplit + 1个元素)

答案 1 :(得分:0)

要分割字符串并在引号内保留空格,可以使用shlex.split()

import shlex
import itertools

s = '''youtube.com.    3599    IN  TXT "google-site-verification=OQz60vR-YapmaVrafWCALpPyA8eKJKssRhfIrzM-DJI"
youtube.com.    3599    IN  TXT "v=spf1 include:google.com mx -all"
youtube.com.    3599    IN  TXT "facebook-domain-verification=64jdes7le4h7e7lfpi22rijygx58j1"'''

out = list(itertools.chain.from_iterable(shlex.split(line, posix=False) for line in s.splitlines()))

print(out)

打印:

['youtube.com.', '3599', 'IN', 'TXT', '"google-site-verification=OQz60vR-YapmaVrafWCALpPyA8eKJKssRhfIrzM-DJI"', 'youtube.com.', '3599', 'IN', 'TXT', '"v=spf1 include:google.com mx -all"', 'youtube.com.', '3599', 'IN', 'TXT', '"facebook-domain-verification=64jdes7le4h7e7lfpi22rijygx58j1"']