Home > Mobile >  how to restructure data in python
how to restructure data in python

Time:11-13

I'm new to Python. I need to restructure the inputed string data into entered/separated by carriage return characters like this one:

Input: D A P U R
       N U W A Y

Output: D   N
        A   U
        P   W
        U   A
        R   Y

I tried to use the replace() method but nothing solved. Below is my current code:

txt = input("Enter text: ")

def textSeparation(txt):
    t = txt.replace(" ", "\r\n")
    return t

res = textSeparation(txt)
print(res)

The inputed string is basicly separated by space characters. Is there any built-in function in Python to do this? Any help would be very appreciated.

Thank you

I have tried using built-in replace() to replace the space char with \r\n but nothing solved.

CodePudding user response:

I am pretty sure there is a better way out there. But here is something that can do the job.

Note: Only works for this particular structure and equal number of characters.

First, I will assume that your input looks something like this:

input_string = "D A P U R\nN U W A Y"

Output:

D A P U R
N U W A Y

What you can do is
1- split the string on the line separator (\n)
2- convert each line to its list of characters
3- convert the result to a numpy array
4- transpose the array
5- join each row to form a string
6- join all rows to form a full string
This is done in this function:

def transpose_input(input_string):
    return '\n'.join([' '.join(l) for l in np.array([list(line.replace(' ', '')) for line in input_string.split('\n')]).T.tolist()])

Test:

input_string = "D A P U R\nN U W A Y"
new_string = transpose_input(input_string)

print(new_string)

Output:

D N
A U
P W
U A
R Y

Edit: without using numpy

def transpose_input(input_string):
    return '\n'.join([' '.join(l) for l in list(zip(*input.replace(' ', '').split('\n')))])

Test:

input_string = "D A P U R\nN U W A Y"
new_string = transpose_input(input_string)

print(new_string)

Output:

D N
A U
P W
U A
R Y

Edit 2: only if space separated

def transpose_input(input_string):
    return '\n'.join([' '.join(l) for l in list(zip(*[r.split(' ') for r in input_string.split('\n')]))])
  • Related