简体   繁体   English

从字符串中删除特定字符

[英]Remove specific character from string

I want to create a function that takes a line from a.txt file and remove double-spaces, but every thing i tried, and found on the internet, removes every instance of the character i want to remove or just the first instance.我想创建一个 function,它从 a.txt 文件中获取一行并删除双空格,但是我尝试并在互联网上找到的每件事都会删除我想要删除的字符的每个实例或只是第一个实例。

    def reduceWhitespace():
        my_file = open("Teste.txt", "r")
        new_line = ""
        old_line = my_file.readline()
        empty_char = ""

        for char in range(len(old_line)):
            if old_line [char] == " ":
                if old_line [char + 1] == " ":
                    new_line = old_line.replace(old_line [char], empty_char)

        print (new_line)
        my_file.close()

    reduceWhitespace()

The output should be the line with no double-spaces: output 应该是没有双空格的行:

"This line has extra space characters" “这一行有多余的空格字符”

But instead it outputs the string with no spaces:但相反,它输出没有空格的字符串:

"Thislinehasextraspacecharacters" “此行有多余的空格字符”

below code will convert multiple space into one space: ( replace_double_space() function will convert multiple space in string into 1)下面的代码会将多个空格转换为一个空格:( replace_double_space() function 会将字符串中的多个空格转换为 1)

def replace_double_space(line):
    while "  " in line:
        line = line.replace("  ", " ")
    return line

my_file = open("Teste.txt", "r")
line = my_file.readline()
print ("before: ", line)

new_line = replace_double_space(line)
print ("after: ", new_line)

execution result:执行结果:

PS E:\> python .\test.py
before:  This line has extra   space   characters
after:  This line has extra space characters

you can try something like this你可以试试这样的

x="aa//a//aa//aa/a//a"
x=x.replace("//","/",x.count("//"))
print(x)

output look like this: aa/a/aa/aa/a/a output 看起来像这样:aa/a/aa/aa/a/a

You could use the built-in replace function.您可以使用内置替换 function。 For example,例如,

str = 'A  line with  single  and double spaces'
str = str.replace('  ', '')
print(str)

This would output 'Aline withsingleand double spaces' .这将是 output 'Aline withsingleand double spaces'

If you just replace them until done, you risk looping back through the line many times.如果您只是替换它们直到完成,您可能会多次循环返回该线路。 Here is a generator based solution:这是一个基于生成器的解决方案:

def singlespacer(s):
    last = None
    for c in s:
        if c == ' ' and last == ' ':
            continue
        last = c
        yield c
    
s = 'This  line  has       extra       spaces'

print (''.join(singlespacer(s)))

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

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