How to replace repeated instances of a character with a single instance of that character in python

前端 未结 11 1458
北海茫月
北海茫月 2020-12-31 00:29

I want to replace repeated instances of the \"*\" character within a string with a single instance of \"*\". For example if the string is \"*

11条回答
  •  长情又很酷
    2020-12-31 00:35

    Lets assume for this sake of this example, your character is a space.

    You can also do it this way:

    while True:
        if "  " in pattern: # if two spaces are in the variable pattern
            pattern = pattern.replace("  ", " ") # replace two spaces with one
        else: # otherwise
            break # break from the infinite while loop
    

    This:

    File Type                       : Win32 EXE
    File Type Extension             : exe
    MIME Type                       : application/octet-stream
    Machine Type                    : Intel 386 or later, and compatibles
    Time Stamp                      : 2017:04:24 09:55:04-04:00
    

    Becomes:

    File Type : Win32 EXE
    File Type Extension : exe
    MIME Type : application/octet-stream
    Machine Type : Intel 386 or later, and compatibles
    Time Stamp : 2017:04:24 09:55:04-04:00
    

    I find this is a little easier than having to muck around with the re module, which can get a little annoying sometimes (I think).

    Hope that was helpful.

提交回复
热议问题