繁体   English   中英

从Python中的字符串中删除特定的模式?

[英]Removing specific pattern from string in Python?

我有一个字符串,例如

'这是一个不错的字符串,末尾有25.6英寸的大小。

双引号之前的数字可以是浮点数或任何长度的整数。 我想删除空格和双引号之间的所有内容。 现在,我正在尝试使用.find()函数来获取双引号和最后一个空格的索引,然后删除这些索引之间的每个符号。 有没有更聪明的方法呢?

我们可以在这里尝试使用re.sub

input = ' This is a nice string with some size in inches at the end 25.6" '
output = re.sub(r'\s+\d+(?:\.\d+)"\s*$', '', input)
print(output)

This is a nice string with some size in inches at the end

正则表达式\\s+\\d+(?:\\.\\d+)"\\s*$表示:

\s+       match one or more spaces
\d+       match one or more digits, followed by
(?:\.\d+) an optional decimal component
"         inches unit sign
\s*       possible trailing whitespace, until
$         the end of the string

暂无
暂无

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

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