python - 将字符串拆分为两个单独的数字和字母列表 -python

标签 python regex string list

标题已经说明了一切。例如: 我要分开

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/

相关文章:

python - Sphinx 中尖括号旁边的替换

python - 如何使用 Django 在 nginx 中设置子目录

javascript - meteor 辅助变量去除重复的相邻空格

java - 而 nextLine() 不等于 ""

python - Jupyter Notebook 中的旧 sklearn 版本

python - pandas.dataframe.query() 中的模式搜索

regex - 范围 0-200.0000(包括 0 和 200)的正则表达式

javascript - 构造具有三个子模式且最大长度为 28 个字符的正则表达式

regex - Grep 语法困境

c++ - 忽略几个不同的词.. c++?