I am reading a text file inside Python that contains salaries and the raise they will receive as a percent. I am trying to multiply the initial salary by the percent and print the salary after the raise has been applied. I keep receiving an error message which is as follows: TypeError: can't multiply sequence by non-int of type 'str'

I realize it is a string and I try to evaluate the numbers but after I evaluate the numbers i receive another error message about an invalid syntax.

This is the code I have:

text_record = open("Employees.txt", "r")

for line in text_record:
    name_DOB_salary = line.split()
    first_name = name_DOB_salary[1]
    last_name = name_DOB_salary[0]
    DOB = name_DOB_salary[2]
    percent = 100 * name_DOB_salary[4]
    initial_money = name_DOB_salary[3]
    final_money = initial_money + (eval(initial_money + percent))
    print 'Employee' , first_name , last_name , 'was born on' , DOB
    print 'At' , percent , '%, the salary will increase from $', initial_money , 'to' , final_money

The text file looks like this:

Jones Martin 12/14/1976 54254.87 .02
Cameron James 9/6/1982 44653.00 .025
Harris Ellen 10/10/1980 36876.50 .03
Forbes Malcolm 4/18/1945 8898765.55 .05
Cooper David 3/23/1979 39999.25 .025

If anyone can help point me in the right on how I can multiply these two figures that would be greatly appreciated. Many thanks!

When you want to perform mathematical operations, remember to cast your string tokens into integer/float using int()/float(). There is no need to use 'eval' in such cases.

I would use ...

# the next 2 items have to be numbers not strings
    increase_rate = float(name_DOB_salary[4])
    initial_money = float(name_DOB_salary[3])
    final_money = initial_money + initial_money*increase_rate

... and then multiply increase_rate by 100 to get percent

Sorry, haven't been on this in a few days and only seen the replies. After much stress I figured out that I was only reading the file and not writing back into it. I made the slight change from

text_record = open("Employees.txt", "r")

to

text_record = open("Employees.txt", "r+")

Using the plus allowed me to write back into the file and evaluate the strings. That was the main problem I was having, was Python would not allow me to evaluate the numbers from strings. Oh and I also improved the printing output using some formated output to bring it all together in a simpler way. Thanks for your reply's though I will keep them in mind for the future!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.