我想用非字母表拆分而不使用import re

时间:2018-03-16 02:37:15

标签: python python-3.x

我已经尝试使用.isalpha()和for或while循环。而且我觉得这很麻烦......我可能不需要收集我发现非人物的地方......差不多两天,我找不到办法。你能给我一些想法吗?

a = []
pos1 = 0
for pos in range(len(string)-1):
    if string[pos1].isalpha():
        pos1 += 1
a.append(pos1)
#I want to return list with string which splited with non alphabet 

例如,

/a#apple;3^%$

应该返回

['/', 'a#', 'apple;3^%$']

如果代码找到字母,那么它会收集以前的字符,就像那样。

提前致谢!

1 个答案:

答案 0 :(得分:1)

以下是您在代码中出错的地方:

a = []
pos1 = 0
# Should use a better variable name, I don't know what's the purpose of this variable
for pos in range(len(string)-1):
    if string[pos1].isalpha(): # Shouldn't this be string[pos]?
        pos1 += 1 # You should append here
a.append(pos1) 
# you append a pos1 (which is a number) into a outside the loop

以下是有效的代码:

string = '/a#apple;3^%$'

a = []
idx = 0
lastidx = 0
while idx < len(string): # loops through string
    while string[idx].isalpha(): # increment idx until we find a non-alphanumeric character
        idx += 1
        if idx >= len(string):break

    while not string[idx].isalpha(): # increment idx until we find an alphanumeric character
        idx += 1
        if idx >= len(string):break
    a.append(string[lastidx:idx]) # add the sliced string from lastidx to idx to a
    lastidx = idx # sets the last index to the current index
print(a)

输出:

['/', 'a#', 'apple;3^%$']

希望这会有所帮助。 : - )