python split拆分字符串_在Python中不使用split()拆分字符串

从一个字符串列表开始,如果您想拆分这些字符串,有两种方法可以这样做,具体取决于您想要的输出是什么。

情况1:一个字符串列表(old_list)拆分为一个新的字符串列表(new_list)。

例如['This is a Sentence', 'Also a sentence']->['This', 'is', 'a', 'Sentence', 'Also', 'a', 'sentence']。

步骤:把绳子绕起来。for sentence in old_list:

创建新字符串以跟踪当前单词(word)。

循环遍历每个字符串中的字符。for ch in sentence:

如果遇到要拆分的字符(本例中为空格),请检查word是否为空并将其添加到新列表中,否则将该字符添加到word。

确保在遍历所有字符后将word添加到列表中。

最终代码:new_list = []

for sentence in old_list:

word = ''

for ch in sentence:

if ch == ' ' and word != '':

new_list.append(word)

word = ''

else:

word += ch

if word != '':

new_list.append(word)

这相当于new_list = []

for sentence in old_list:

new_list.extend(sentence.split(' '))

或者更简单new_list = ' '.join(old_list).split(' ')

情况2:一个字符串列表(old_list)拆分为一个新的字符串列表(new_list)。

例如['This is a Sentence', 'Also a sentence']->[['This', 'is', 'a', 'Sentence'], ['Also', 'a', 'sentence']]。

步骤:把绳子绕起来。for sentence in old_list:

创建一个新字符串来跟踪当前单词(word)和一个新列表来跟踪此字符串中的单词(sentence_list)。

循环遍历每个字符串中的字符。for ch in sentence:

如果遇到要拆分的字符(本例中为空格),请检查word是否为空并将其添加到sentence_list,否则将该字符添加到word。

确保在遍历所有字符后将word添加到sentence_list。

Append(不是extend)sentence_list到新列表并移到下一个字符串。

最终代码:new_list = []

for sentence in old_list:

sentence_list = []

word = ''

for ch in sentence:

if ch == ' ' and word != '':

sentence_list.append(word)

word = ''

else:

word += ch

if word != '':

sentence_list.append(word)

new_list.append(sentence_list)

这相当于new_list = []

for sentence in old_list:

new_list.append(sentence.split(' '))

或使用列表理解new_list = [sentence.split(' ') for sentence in old_list]

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值