获取字符串的子字符串

2024-04-25 14:15:04 发布

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

例如:string='AbcDEfGhIJK'

我想取一份清单,上面有: ['A'、'bc'、'DE'、'f'、'G'、'h'、'IJK']

我正试着想一个这样做的逻辑,但到目前为止没有运气。你知道吗

编辑: 我不懂正则表达式,所以我只用循环 这就是我想出来的,但它没有给出最后一个“IJK”

u_count = 0 
l_count = 0 
l_string = '' 
u_string = '' 
output = []

data = 'AbcDEfGhIJK'

for c in data:
 if(c.isupper()):
    if(l_count !=0):
        output.append(l_string)
        l_count = 0
        l_string = ''
    u_string += c
    u_count += 1

 if(c.islower()):
    if(u_count !=0):
        output.append(u_string)
        u_count = 0
        u_string = ''
    l_string +=c
    l_count += 1
print(output)

Tags: in编辑foroutputdatastringifcount
3条回答

您可以使用itertools.groupby来实现这一点:

from itertools import groupby

string = 'AbcDEfGhIJK'
out = [''.join(group) for key, group in groupby(string, key=lambda c: c.islower())]
print(out)
# ['A', 'bc', 'DE', 'f', 'G', 'h', 'IJK']

这里,groupby将给islower()提供相同输出的字符分组

str = 'AbcDEfGhIJK'
str=list(str)
for k,v in enumerate(str[:-1]):
    joined=''.join([str[k],str[k+1]])
    if joined.isupper() or joined.islower():
        str[k+1]=joined
        str[k]=''
str=[x for x in str if x!='']
print(str)

输出

['A', 'bc', 'DE', 'f', 'G', 'h', 'IJK']

您可以使用正则表达式:

import re

text = 'AbcDEfGhIJK'

result = re.split('([a-z]+)', text)
print(result)

输出

['A', 'bc', 'DE', 'f', 'G', 'h', 'IJK']

其思想是按小写字母'([a-z]+)'拆分字符串,但保留拆分模式。你知道吗

相关问题 更多 >