Home > Software design >  How to move a white space in a string?
How to move a white space in a string?

Time:05-17

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:]

E.g.: 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!

CodePudding user response:

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:]

CodePudding user response:

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

CodePudding user response:

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.
  • Related