You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中移除字符串空格至双引号间内容的高效方法?

更简便的处理方法:正则表达式或字符串分割

嘿,你完全不用手动折腾索引位置!针对这个需求,有两种更简洁的思路:

方法一:正则表达式(最灵活)

正则可以精准匹配末尾的「空格 + 整数/浮点数 + 双引号」模式,直接替换掉你想移除的部分,代码非常简洁:

场景1:移除空格与引号之间的数字(保留空格和引号)

如果你想把 ...end 25.6" 变成 ...end ",可以这么写:

import re
original_str = ' This is a nice string with some size in inches at the end 25.6" '
processed_str = re.sub(r'\s+\d+(\.\d+)?"$', ' "', original_str)
print(processed_str)
# 输出:' This is a nice string with some size in inches at the end " '

场景2:直接去掉整个末尾的尺寸部分(包括空格和引号)

如果你的目标是得到纯文本部分,去掉末尾的尺寸标记,可以把替换目标改成空字符串:

import re
original_str = ' This is a nice string with some size in inches at the end 25.6" '
processed_str = re.sub(r'\s+\d+(\.\d+)?"$', '', original_str)
print(processed_str)
# 输出:' This is a nice string with some size in inches at the end '

正则表达式的含义拆解:

  • \s+:匹配一个或多个空格(覆盖末尾可能的多个空格)
  • \d+:匹配整数部分的一个或多个数字
  • (\.\d+)?:可选的小数部分(?表示这部分可以不存在,兼容整数的情况,比如5")
  • "$:匹配字符串结尾的双引号,$锚定到字符串末尾,避免误匹配中间的引号

方法二:字符串分割(适合结构固定的场景)

如果你的字符串末尾的尺寸格式非常固定(一定是「空格 + 数字 + 引号」结尾),也可以用rsplit从右侧分割一次,直接取前面的文本:

original_str = ' This is a nice string with some size in inches at the end 25.6" '
# 从右侧按空格分割1次,取第一部分
processed_str = original_str.rsplit(' ', 1)[0]
print(processed_str)
# 输出:' This is a nice string with some size in inches at the end '

这种方法不用导入模块,代码更轻量,但正则的兼容性更强——比如如果末尾有多个空格,或者数字格式有变化,正则都能轻松处理。

对比你现在用的find方法,这两种方式都不用手动计算索引位置,代码更简洁,也更不容易出错~

内容的提问来源于stack exchange,提问作者milka1117

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:25:55