📜  Python|从字符串列表中拆分字符串和数字

📅  最后修改于: 2022-05-13 01:54:23.383000             🧑  作者: Mango

Python|从字符串列表中拆分字符串和数字

有时,在使用字符串列表时,我们可能会遇到需要从数字列表中删除周围的杂散字符或噪音的问题。这可以是货币前缀、数字符号等形式。让我们讨论一种可以执行此任务的方式。

方法:使用列表理解 + strip() + isdigit() + join()
上述功能的组合可用于执行此任务。在此,我们从字符串中识别出的数字中去除杂散字符并返回结果。

# Python3 code to demonstrate working of
# Extract digit from string list 
# using list comprehension + strip() + isdigit() + join()
from itertools import groupby
  
# initialize list 
test_list = ["-4", "Rs 25", "5 kg", "+15"]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Extract digit from string list 
# using list comprehension + strip() + isdigit() + join()
res = [''.join(j).strip() for sub in test_list 
        for k, j in groupby(sub, str.isdigit)]
  
# printing result
print("List after removing stray characters : " + str(res))
输出 :
The original list : ['-4', 'Rs 25', '5 kg', '+15']
List after removing stray characters : ['-', '4', 'Rs', '25', '5', 'kg', '+', '15']