Python 字符串去除字符串中的一个制表符

1 投票
4 回答
2076 浏览
提问于 2025-04-17 13:15

我有一个字符串,内容是:

 "This is a small \t\t world"

假设这个字符串在“small”和“world”之间有两个制表符(也就是空白)。我想要去掉其中一个制表符,这样我就能得到:

 "This is a small \t world"

在这个句子里,“small”和“world”这两个词只能出现一次。简单来说,给定这两个特定的词,我想去掉它们之间多余的制表符。

4 个回答

1

使用 regex(正则表达式):

In [114]: def func(st,*words):
    rep=" \t ".join(words)
    reg="\b%s\s?\t{1,}\s?%s\b"%(words[0],words[1])
    return re.sub(reg,rep,st)
   .....: 

In [118]: strs='This is \t\t\t a small\t\t\tworld, very small world?'

In [119]: func(strs,"small","world")
Out[119]: 'This is \t\t\t a small \t world, very small world?'

In [120]: func(strs,"is","a")
Out[120]: 'This is \t a small\t\t\tworld, very small world?'
1

在编程中,有时候你会遇到一些问题,可能是因为代码写得不够好,或者是使用的工具不太合适。比如,有些人可能会在使用某个库的时候,发现它的功能不够强大,或者不太符合自己的需求。这种情况下,大家通常会在网上寻找解决方案,比如在StackOverflow上提问。

在提问的时候,最好能把问题描述得清楚一些,像是你遇到了什么具体的错误,或者你希望实现什么样的功能。这样,其他人才能更好地理解你的问题,并给出有效的建议。

另外,分享一些代码片段也是很有帮助的。这样别人可以直接看到你是怎么写的,可能就能更快地找到问题所在。

总之,提问的时候要尽量详细,提供足够的信息,这样才能得到更好的帮助。

def remove_tab(st, word1, word2):
    index1 = st.find(word1)
    index2 = st[index1:].find(word2)
    replacement = st[index1:index2].replace('\t\t', '\t')
    return st[:index1] + replacement + st[index2:]
2

使用 re 模块...

import re

s = b"This is        a small         world"

s = re.sub(r'(.*\bsmall *)\t+( *world\b.*)', r'\1\t\2', s)

print s

输出结果:

>>> 
This is          a small     world

这样做会保留两个 tabs 前后的所有空格。

撰写回答