简体   繁体   中英

How to move a white space in a string?

I need to move a whitespace in a string one position to the right. This is my code:

for i in range(0,len(resultaat)):
    if resultaat[i] == " ":
        string = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:]

Eg: If resultaat =

"TH EZE NO  FPYTHON."

Than my output needs to be:

'THE ZEN OF PYTHON.'

, but the output that I get is:

"TH EZE NO F PYTHON."

I think this happened because the loop undid the action where it moved the previous space. I don't know how to fix this problem. Can someone help me with this?

Thanks!

Each time through the loop you're getting slices of the original resultaat string, without the changes you've made for previous iterations.

You should copy resultaat to string first, then use that as the source of each slice so you accumulate all the changes.

string = resultaat
for i in range(0,len(resultaat)):
    if resultaat[i] == " ":
        string = string[:i] + string[i+1] + " " + string[i+2:]

You could do something like this:

# first get the indexes that the character you want to merge
indexes = [i for i, c in enumerate(resultaat) if c == ' ']
for i in indexes: # go through those indexes and swap the characters as you have done
    resultaat = resultaat[:i] + resultaat[i+1] + " " + resultaat[i+2:] # updating resultaat each time you want to swap characters

Assuming the stated input value actually has one more space than is actually needed then:

TXT = "TH EZE NO FPYTHON."

def process(s):
    t = list(s)
    for i, c in enumerate(t[:-1]):
        if c == ' ':
            t[i+1], t[i] = ' ', t[i+1]
    return ''.join(t)

print(process(TXT))

Output:

THE ZEN OF PYTHON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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