lovychen

python 提取一段字符串中去数字

ss = “123ab45”

方法一:filter

filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

str.filter:如果字符串只包含数字则返回 True 否则返回 False。

filter(str.isdigit, ss)

python2 和 python 3 用起来有差别

# one (python2 中)
>>> filter(str.isdigit, \'123ab45\')
\'12345\'
#one1 (python3 中)
>>> "".join(list(filter(str.isdigit, \'123ab45\')))
\'12345\'

#two 
def not_empty(s):
  return s and s.strip()

filter(not_empty, [\'A\', \'\', \'B\', None, \'C\', \' \'])
# 结果: [\'A\', \'B\', \'C\'] 
# 列表中的每个元素都会过一遍 pattern,返回的还是列表

 

方法二:正则表达式

s = re.findall("\d+",ss)[0]
print s

 

分类:

技术点:

相关文章:

  • 2022-01-01
  • 2021-12-22
  • 2022-12-23
  • 2021-12-22
猜你喜欢
  • 2021-06-14
  • 2022-03-11
  • 2022-12-23
  • 2021-07-04
  • 2022-12-23
  • 2022-01-01
  • 2021-06-09
相关资源
相似解决方案