1

I'm working on file contains a few lines of numerical sequences. I want to multiply some part of this string. How am I supposed to do it? When I just do 'num[10:](which is for ex 2)*4' (like below) it prints me '2' four times, I want to print 8.

import os
from datetime import date

with open('C:\\Users\\X\\Desktop\\python\\Y\\Z.txt') as file:
    numbers = file.readlines()


def last_number():
    for num in numbers:
        last = num[10:]
        x = last*4
        print(x)
last_number()    
poloOlo
  • 43
  • 5

1 Answers1

1

When reading a file you read it in string format. In order to do math operations with the content you must convert it to an int or a float.

Specifically if you know the exact location of the numbers in your code you should try this, notice i also sent numbers as a parameter for the function:

import os
from datetime import date

with open('C:\\Users\\X\\Desktop\\python\\Y\\Z.txt') as file:
    numbers = file.readlines()


def last_number(numbers):
    # numbers = [int(num) for num in numbers]
    # prev line will create a list of numbers in integer form for you
    for num in numbers:
        last = int(num[10:])
        x = last*4
        print(x)
last_number()    
Isdj
  • 1,835
  • 1
  • 18
  • 36