标题已经说明了一切。例如: 我要分开
stringtosplit = 'hello57world'
进入
letters = ['h','e','l','l','o','w','o','r','l','d']
numbers = ['5', '7']
然后将它们都恢复为字符串,
letters = 'helloworld'
numbers = '57'
有什么巧妙方法可以做到这一点吗?我想让我的代码尽可能简洁。数字和字母可以出现在字符串中的任何位置,空格和特殊字符已被过滤掉。
最佳答案
>>> stringtosplit = 'hello57world'
>>> letters = []
>>> numbers = []
>>> for k in stringtosplit:
... if k.isalpha() == True:
... letters.append(k)
... elif k.isdigit() == True:
... numbers.append(k)
...
>>> letters
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
>>> numbers
['5', '7']
>>> letters = ''.join(letters)
>>> numbers = ''.join(numbers)
>>> letters
'helloworld'
>>> numbers
'57'
使用str.isalpha检查变量是否是字母,并且 str.isdigit检查它是否是一个数字。然后使用 ''.join(str)
将 list
转换为 str
。
关于python - 将字符串拆分为两个单独的数字和字母列表 -python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23024942/