Input : "A32B45C3"
Output : letters = [ "A", "B", "C"]
numbers = ["32","45","3"]
我尝试使用
code = "A32B45C3"
letters = []
numbers = []
for i in code:
if i.isalpha() == True:
letters.append(i)
elif i.isdigit() == True:
numbers.append(i)
print letters
print numbers
但我得到数字= [" 3"," 2"," 4"," 5"," 3& #34;]而不是[" 32"," 45"," 3"]
答案 0 :(得分:1)
为您创建了一个小代码,如果您不想使用正则表达式。
您可以进一步优化它:
a = "A32B45C3"
numbers = []
strings = []
same_as_prev = True
tmp = ''
for i in a:
if tmp:
same_as_prev = tmp.isalpha() == i.isalpha()
if same_as_prev:
tmp += i
else:
if tmp.isalpha():
strings.append(tmp)
else:
numbers.append(tmp)
tmp = i
same_as_prev = True
# Insert unused tmp.
if tmp:
if tmp.isalpha():
strings.append(tmp)
else:
numbers.append(tmp)
print numbers
print strings
答案 1 :(得分:0)
您当前的方法存在的问题是您正逐字符处理字符串并收集单个字母和数字。
相反,您可以使用re.findall()
查找大写字母后面的一个或多个数字,然后"解压缩"结果分别写成字母和数字:
>>> import re
>>>
>>> s = "A32B45C3"
>>> letters, numbers = zip(*re.findall(r"([A-Z])([0-9]+)", s))
>>> letters
('A', 'B', 'C')
>>> numbers
('32', '45', '3')
答案 2 :(得分:0)
试试这个,
import re
input = "A32B45C3"
letters = filter(None,re.split('[0-9]',input))
numbers = filter(None,re.split('[A-Z]',input))