Home > Software engineering >  Removing decimals from strings
Removing decimals from strings

Time:11-17

I'm having an introductory course in python right now and i get into some troubles with the task.

I have two strings in format:

a b c d e  
f g h i l

I need to get this strings from .txt file,convert them as matrix to vertical format like this:

a f
b g
c h
d i
e l

and put into another .txt file, without using the numpy and pandas libraries. The problem is that from matrix like this:

1 2 3 4 5 
6 7 8 9 10 

where each number don't have to be an integer, i need to get this matrix:

1 6
2 7
3 8 
4 9
5 10

and right now i can get only that with decimals:

1.0 6.0
2.0 7.0
3.0 8.0
4.0 9.0
5.0 10.0

So, from my POW, i need to somehow remove the .0 from the final result, but i dk how i can remove decimals from the strings, consisted with float numbers.

Here goes my code:

with open('input.txt') as f:
    Matrix = [list(map(float, row.split())) for row in f.readlines()]
TrMatrix=[[Matrix[j][i] for j in range(len(Matrix))] for i in range(len(Matrix[0]))]
file=open('output.txt','w')
for i in range(len(TrMatrix)):
    print(*TrMatrix[i],file=file)

CodePudding user response:

Here is the solution as much as I understand your problem

with open('input.txt') as f:
    cols = []
    for row in f.readlines():
        col = [int(float(i)) for i in row.split()]
        cols.append(col)
new_rows = []
for i in range(len(cols[0])):
    new_rows.append(' '.join([str(col[i]) for col in cols]))
Tr_matrix = '\n'.join(new_rows)
with open('output.txt','w') as file:
    file.write(Tr_matrix)
print(Tr_matrix)

Input:

1 2 3 4.6 5.4 
6 7 8 9 10 

Output:

1 6
2 7
3 8
4 9
5 10

CodePudding user response:

Change float to int. float contains decimals. int does not.

  • Related