【问题标题】:Slice a string into two chunks of different lengths based on character in Python基于Python中的字符将字符串切成两个不同长度的块
【发布时间】:2021-01-20 17:34:40
【问题描述】:

所以我有一个看起来像这样的文件:

oak
elm
tulip
redbud
birch

/plants/

allium
bellflower
ragweed
switchgrass

我要做的就是将树木和草本植物分成两块,这样我就可以像这样分别调用它们:

print(trees)
oak
elm
tulip
redbud
birch

print(herbs)
allium
bellflower
ragweed
switchgrass

正如您在示例数据中看到的,数据块的长度不相等,因此我必须根据分隔符“/plants/”进行拆分。如果我尝试拼接,数据现在只是用空格分隔:

for groups in plant_data:
    groups  = groups.strip()
    groups = groups.replace('\n\n', '\n')
    pos = groups.find("/plants/") 
    trees, herbs = (groups[:pos], groups[pos:])
print(trees)
oa
el
tuli
redbu
birc



alliu
bellflowe
ragwee
switchgras

如果我尝试简单地拆分,我会得到列表(这对我的目的来说是可以的),但它们仍然没有分成两组:

for groups in plant_data:
    groups  = groups.strip()
    groups = groups.replace('\n\n', '\n')
    trees = groups.split("/plants/")
print(trees)
['oak']
['elm']
['tulip']
['redbud']
['birch']
['']
['', '']
['']
['allium']
['bellflower']
['ragweed']
['switchgrass']

要删除我认为是问题的空行,我尝试了以下操作:How do I remove blank lines from a string in Python? 而且我知道这里也有类似的问题:Python: split a string by the position of a character

但是我很困惑为什么我不能让这两个分开。

【问题讨论】:

    标签: python python-3.x string split splice


    【解决方案1】:
    spam = """oak
    elm
    tulip
    redbud
    birch
    
    /plants/
    
    allium
    bellflower
    ragweed
    switchgrass"""
    
    spam = spam.splitlines()
    idx = spam.index('/plants/')
    trees, herbs = spam[:idx-1], spam[idx+2:]   
    print(trees)
    print(herbs)
    

    输出

    ['oak', 'elm', 'tulip', 'redbud', 'birch']
    ['allium', 'bellflower', 'ragweed', 'switchgrass']
    

    当然,您可以使用不同的方法(例如列表理解)删除空 str,而不是使用 idx-1、idx+2

    spam = [line for line in spam.splitlines() if line]
    idx = spam.index('/plants/')
    trees, herbs = spam[:idx], spam[idx+1:]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多