繁体   English   中英

替换 function 以删除 python 中除数字和小数点之外的所有内容

[英]Replace function to remove everything but numbers and decimal point in python

我想在没有任何外部库的情况下从字符串中删除除 python 中的数字和小数点之外的所有内容。

我有一个字符串列表,其中包含具有以下模式的长度、宽度和高度。

注意:某些字符串可能包含随机数量的空格

我的演示字符串及其模式

length_string = " length 0.7l"
width_string = " width 0.5w"
height_string = "   height 1h"

到目前为止我已经尝试过:

# The code below is not working due to the pattern of the characters.
length_number = length_string.replace(" length ", "").rstrip("l")
width_number = width_string.replace(" width ", "").rstrip("w")
height_number = height_string.replace("   height ", "").rstrip("h")

期望的结果:

length_number = "0.7"
width_number = "0.5"
height_number = "1"

这看起来像是正则表达式的工作:

import re

def remove_chars(entry):
    x = re.sub('[a-zA-Z\s]', '', entry)
    return(x)

length_string = " length 0.7l"
width_string = " width 0.5w"
height_string = "   height 1h"

remove_chars(length_string)
#0.7
remove_chars(width_string)
#0.5
remove_chars(height_string)
#1

我建议您花一些时间阅读正则表达式,以确保您了解它们的工作原理,以便如果出现您所显示的规则的异常,您可以开始尝试处理它,但基本上是上面的代码将任何字母字符 ( a-zA-z ) 或空格 ( \s ) 替换为'' 如果您有其他特殊字符,例如%; @ ,基本上任何不是字母或空格的东西,或者如果你的字符串中有其他数字,你将不会得到任何有用的东西,就像当前正则表达式的写法一样。

我猜你也不想使用正则表达式,它内置在 python中,非常适合这种方法。

这将是我没有任何库的方法,您只需拥有一个包含所有有效字符的列表(或者如果您在 if 中放置一个 not 则无效)并遍历字符串。

   valid_chars = [str(i) for i in range(11)] + ["."]
   new_string = ""
   sample = " length 0.7l"
   for char in sample:
    if char in valid_chars:
        new_string += char

用字符串拉出一个或多个数字

length_string = " length 0.7l"
width_string = " width 0.5w"
height_string = "   height 1h"
length_string = [i for i in (''.join((ch if ch in '0123456789.-e' else ' ') for ch in length_string)).split()]
width_string = [i for i in (''.join((ch if ch in '0123456789.-e' else ' ') for ch in width_string)).split()]
height_string = [i for i in (''.join((ch if ch in '0123456789.-e' else ' ') for ch in height_string)).split()]
if 'e' in length_string:
    length_string.remove('e')
if 'e' in width_string:
    width_string.remove('e')
if 'e' in height_string:
    height_string.remove('e')

暂无
暂无

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

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