字符串的特定拆分

2024-06-13 07:48:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个字符串:

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"]

使用string的split()函数,它会将每一个由空格分隔的字符串拆分,但我希望将每一行拆分为5个由一行中的前4个空格分隔的字符串。 这怎么可能?(最好代码不多)

提前谢谢大家,, 问候


Tags: 字符串intxtcomincludeyoutubegooglesite
2条回答

要拆分字符串并在引号内保留空格,可以使用^{}

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"']

可以使用^{}定义最大拆分数

my_string.split(maxsplit=4)

If maxsplit is given, at most maxsplit number of splits occur, and the remainder of the string is returned as the final element of the list (thus, the list will have at most maxsplit+1 elements)

相关问题 更多 >