简体   繁体   English

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

[英]Removing specific pattern from string in Python?

I have a string such as 我有一个字符串,例如

' This is a nice string with some size in inches at the end 25.6" ' '这是一个不错的字符串,末尾有25.6英寸的大小。

Number before the double quotes might be float or integer of any length. 双引号之前的数字可以是浮点数或任何长度的整数。 I want to remove everything between a space and double quote sign. 我想删除空格和双引号之间的所有内容。 Right now I am trying to do something with .find() functions to get the index of double quote sign and the last space and then to remove each symbol between those indexes. 现在,我正在尝试使用.find()函数来获取双引号和最后一个空格的索引,然后删除这些索引之间的每个符号。 Is there any smarter way to do so? 有没有更聪明的方法呢?

We can try using re.sub here: 我们可以在这里尝试使用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

The regex pattern \\s+\\d+(?:\\.\\d+)"\\s*$ says to: 正则表达式\\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