python - 基于Python中的字符将字符串切成两个不同长度的块
问题描述
所以我有一个看起来像这样的文件:
oak
elm
tulip
redbud
birch
/plants/
allium
bellflower
ragweed
switchgrass
我要做的就是将树木和草本植物分成两块,这样我就可以像这样分别调用它们:
print(trees)
oak
elm
tulip
redbud
birch
print(herbs)
allium
bellflower
ragweed
switchgrass
正如您在示例数据中看到的那样,数据块的长度不等,因此我必须根据分隔符“/植物/”进行拆分。如果我尝试拼接,数据现在只是用空格分隔:
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']
为了删除我认为是问题的空行,我尝试了以下操作:如何从 Python 中的字符串中删除空行? 而且我知道在这里用一个字符分割一个字符串也被问过类似的问题:Python: split a string by the position of a character
但是我很困惑为什么我不能让这两个分开。
解决方案
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:]
推荐阅读
- python - 更改循环提示
- c# - 此类型名称中的 #(哈希)是什么意思?
- php - 我可以通过检查我的数据库有多少行来获得 SQL 注入吗?
- angular - ie11中的Angular ngModel选择
- database - 如何将访问备份为压缩文件?
- javascript - 如何使用 Google Apps 脚本对 SaxoTrader 进行身份验证
- python - 如何将整个numpy数组作为python中的参数传递给用户定义的函数?
- java - 带有时间和星期几的 JAVA 日历范围
- powershell - 如何更快地批量运行powershell命令?
- laravel - laravel 私信