在Python中不使用split()函数分割字符串

3

除了使用split()方法外,还有哪些其他方法可以拆分字符串?例如,如何在不使用split()方法的情况下将['This is a Sentence']拆分为['This','is','a','Sentence']?


1
你不能使用split()函数来分割一个列表。 - midori
10个回答

11
sentence = 'This is a sentence'
split_value = []
tmp = ''
for c in sentence:
    if c == ' ':
        split_value.append(tmp)
        tmp = ''
    else:
        tmp += c
if tmp:
    split_value.append(tmp)

我很感激你的帮助,但是当我运行代码时,它输出了 ['This', 'is', 'a'],但是某种原因它省略了'Sentence'。有什么原因吗?我已经逐行运行了每一行代码,但是我无法找出问题所在。 - swimdawg12

3

如果您需要,可以使用正则表达式:

>>> import re
>>> s = 'This is a Sentence'
>>> re.findall(r'\S+', s)
['This', 'is', 'a', 'Sentence']
\S 表示任何非空格字符,+ 表示查找一个或多个连续的这样的字符。re.findall 将创建一个匹配该模式的所有字符串的列表。s.split() 实际上是最好的方法。

2
一种递归版本,详细分解步骤如下:
def my_split(s, sep=' '):
    s = s.lstrip(sep)
    if sep in s:
        pos = s.index(sep)
        found = s[:pos]
        remainder = my_split(s[pos+1:])
        remainder.insert(0, found)
        return remainder
    else:
        return [s]

print my_split("This is a sentence")

或者,简洁的一行表单:
def my_split(s, sep=' '):
    return [s[:s.index(sep)]] + my_split(s[s.index(sep)+1:]) if sep in s else [s]

1
sentence = 'This is a sentence'
word=""
for w in sentence :
    if w.isalpha():
        word=word+w

    elif not w.isalpha():
      print(word)
      word=""
print(word)

1

如果您有一个字符串列表,想要将这些字符串拆分成若干个单词,根据您的需求,有几种不同的方法可以实现。

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

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

步骤:

  1. 循环遍历字符串。 for sentence in old_list:
  2. 创建一个新字符串来跟踪当前的单词(word)。
  3. 循环遍历每个字符串中的字符。 for ch in sentence:
  4. 如果您遇到要拆分的字符(在此示例中为空格),请检查word是否为空,并将其添加到新列表中;否则,请将该字符添加到word中。
  5. 确保在循环遍历所有字符后将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']]

步骤:

  1. 循环遍历字符串。 for sentence in old_list:
  2. 创建一个新字符串来跟踪当前单词(word)和一个新列表来跟踪该字符串中的单词(sentence_list)。
  3. 循环遍历这些字符串中的每个字符。 for ch in sentence:
  4. 如果您遇到要拆分的字符(例如空格),请检查word是否为空并将其添加到sentence_list,否则将字符添加到word
  5. 确保在循环遍历所有字符后将word添加到sentence_list
  6. append(而不是extendsentence_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
请考虑编辑您的帖子,添加更多关于代码的解释以及为什么它可以解决问题的说明。一个主要只包含代码(即使它是有效的)的答案通常不能帮助提问者理解他们的问题。 - SuperBiasedMan

1
def mysplit(strng):
    strng = strng.lstrip() 
    strng = strng.rstrip()
    lst=[]
    temp=''
    for i in strng:
        if i == ' ':
            lst.append(temp)
            temp = ''
        else:
            temp += i
    if temp:
        lst.append(temp)
    return lst
     
print(mysplit("Hello World"))
print(mysplit("   "))
print(mysplit(" abc "))
print(mysplit(""))

1
string1 = 'bella ciao amigos'
split_list = []
tmp = ''
for s in string1:
   if s == ' ':
       split_list.append(tmp)
       tmp = ''
   else:
       tmp += s
if tmp:
   split_list.append(tmp)

print(split_list)

输出:

输出: ------> ['bella', 'ciao', 'amigos']

reverse_list = split_list[::-1]
print(reverse_list)

输出:

输出: ------> ['amigos', 'ciao', 'bella']


1
这是一个简单的代码,用于从字符串值中分离出一个字符值;即
输入:UDDDUDUDU
s = [str(i) for i in input().strip()]
print(s)

输出:['U','D','D','D','U','D','U','D','U']


你知道,他们不想使用strip()。只是提醒一下。 - user14638282

0

这是最准确的split方法副本之一:

def splitter(x, y = ' '):
    l = []
    for i in range(x.count(y) + 1):
        a = ''
        for i in x:
            if i == y: break
            a += i
        x = x[len(a) + 1 : len(x)]
        l.append(a)
    return ([i for i in l if i != ''])

-1
my_str='This is a sentence'
split_value = []
tmp = ''
for i in my_str+' ':
    if i == ' ':
        split_value.append(tmp)
        tmp = ''
    else:
        tmp += i   
print(split_value)

只需要对已经给出的代码进行小修改即可


你能解释一下为什么你的代码比已经被接受的五年老答案更好吗?你认为将“c”的名称更改为“i”真的会带来任何价值吗? - AlexT
我不知道我的代码是否更好,我只是认为去掉一个额外的if条件可以缩短代码而已。 - Junaid Ahmad
如果您编辑答案并解释为什么添加末尾的空格可以消除最后一个if语句的需要,那么它将成为一个正确的答案,并且会得到加号而不是减号。 - AlexT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接