繁体   English   中英

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

[英]Splitting a string into a two separate lists of numbers and letters -python

标题说明了一切。 例如:我要拆分

stringtosplit = 'hello57world' 

letters = ['h','e','l','l','o','w','o','r','l','d']
numbers = ['5', '7']

然后把它们都放回弦中

letters = 'helloworld'
numbers = '57'

有什么整洁的方法吗? 我想让我的代码尽可能简洁。 数字和字母可以出现在字符串和空格的任何位置,特殊字符已经被过滤掉。

通常,您可以这样做:

>>> stringtosplit = 'hello57world'
>>> onlyLetter = "".join([i for i in stringtosplit if i.isalpha()])
>>> onlyLetter
'helloworld'
>>> onlyDig = "".join([i for i in stringtosplit if i.isdigit()])
>>> onlyDig

函数i.isalpha()将测试i是否为字母,而i.isdigit()将测试i是否为数字。

使用str.joinstr.isalphastr.isdigit和生成器理解:

>>> s = 'hello57world'
>>> alphas = ''.join(c for c in s if c.isalpha())
>>> nums = ''.join(c for c in s if c.isdigit())
>>> print alphas, nums
helloworld 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

import string

letters = []
numbers = []

for achar in thestring:
    if achar in string.ascii_letters:
        letters.append(achar)
    if achar in string.digits:
        letters.append(achar)

letters_string = "".join(letters)
numbers_string = "".join(numbers)

使用正则表达式:

import re

stringtosplit = 'hello57world'
letters = ''.join(re.findall('([a-zA-Z])', stringtosplit))
numbers = ''.join(re.findall('([0-9])', stringtosplit))

工具:

  1. 您应该将此Python正则表达式与group一起使用。 我相信这将提供大多数清除方式:

     r = r"(?P<first>[az]*)(?P<num>[0-9]*)(?P<last>[az]*)" # ^^^^^ ^^^^ ^^^ # before numbers numbers after numbers # any group can be absent 
  2. 然后,您可以使用re.findall(pattern, string, flags=0)

    返回字符串中模式的所有非重叠匹配项,作为字符串列表。 从左到右扫描该字符串,并以找到的顺序返回匹配项。 如果该模式中存在一个或多个组,则返回一个组列表;否则,返回一个列表。 这将是一个元组列表。 如果模式有多个组。 空匹配项将包括在结果中,除非它们碰到另一个匹配项的开头。

测试用例:

>>> re.findall(r, 'hello57world')[0]  # your string 
('hello', '57', 'world')
>>> re.findall(r, 'hello57')[0]  # word after number ""
('hello', '57', '')
>>> re.findall(r, '3234abcd')[0] # word before number ""
('', '3234', 'abcd')
>>> re.findall(r, '450')[0]  # only number
('', '450', '')
>>> re.findall(r, 'hello')[0]  # number is ""
('hello', '', '')
>>> re.findall(r, '')[0] # empty string
('', '', '')

码:
现在,您可以用三行代码编写简单的代码:

>>> stringtosplit = 'hello57world' 
>>> r = r"(?P<first>[a-z]*)(?P<num>[0-9]*)(?P<last>[a-z]*)"
>>> f, n, l = re.findall(r, stringtosplit)[0]
>>> n
'57'
>>> f + l
'helloworld'

试试看!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM