how can i remove the extra space in my output?

Question:

I’m using the following code to get the mean of an array made with user input .

import numpy as np

n, p = [int(x) for x in input().split()]

lst = []

d = (n*p)/2

for i in range(int(d)):

ele = input().split()

lst.append(ele)
if len(lst) == (d):
    break

x_arr = np.array(lst)

x_arr.reshape(n, p)

x_arr_new = x_arr.astype(float)

y = x_arr_new.mean(axis=1)
print(y)

for example i Input this :

3 2

1 2

1 0.5

1 0.3

the OUTPUT that i have is this :

[1.5 0.75 0.65]

while the OUTPUT that i want is this :

[1.5 0.75 0.65]

Notice the difference in spaces between the first and second OUTPUT after the first number

Asked By: lil2big

||

Answers:

Use just have to create custom string object instead of calling inbuilt numpy __str__ method return string object. For that use have to add this line of code :

y = [str(i) for i in y]

FINAL CODE

import numpy as np
n, p = [int(x) for x in input().split()]
lst = []
d = (n*p)/2
for i in range(int(d)):
    ele = input().split()
    lst.append(ele)

x_arr = np.array(lst)
x_arr.reshape(n, p)
x_arr_new = x_arr.astype(float)
y = x_arr_new.mean(axis=1) 
y = [str(i) for i in y]
print(' '.join(y))
Answered By: Martian Coder

as I wanted the answer to be in the form of a list without two spaces after the first number, I did the following

import numpy as np

n, p = [int(x) for x in input().split()]

lst = []

d = (n*p)/2

for i in range(int(d)):
    ele = input().split()
    lst.append(ele)
    if len(lst) == (d):
        break

x_arr = np.array(lst)

x_arr.reshape(n, p)

x_arr_new = x_arr.astype(float)

y = x_arr_new.mean(axis=1)

k = []

for t in y:
   k.append(t)

k_arr = np.array(str(k))

b = ''.join(str(k).split(','))

print(b)

the input will be

3 2

1 3

1 0.5

===========

the OUTPUT will be

[2.0 0.65 0.75]

without any space

of course I’m a beginner so forgive me for the crude code

Answered By: lil2big
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.