Home > Back-end >  Python issue with string conversion
Python issue with string conversion

Time:11-04

I have a list like this:

[[30, '10', '10', '10'], [27, '10', '10', '7'], [27, '9', '8', '10'], [25, '9', '9', '7'], [25, '7', '10', '8'], [25, '8', '10', '7'], [24, '7', '10', '7'], [24, '8', '9', '7'], [24, '6', '10', '8'], [24, '4', '10', '10'], [24, '9', '10', '5'], [24, '7', '7', '10'], [24, '10', '10', '4'], [23, '3', '10', '10'], [23, '6', '9', '8'], [23, '8', '5', '10'], [23, '9', '8', '6'], [23, '8', '7', '8'], [22, '10', '3', '9'], [22, '3', '10', '9'], [22, '4', '8', '10'], [22, '8', '6', '8'], [22, '10', '10', '2'], [21, '9', '4', '8'], [21, '8', '4', '9'], [21, '6', '6', '9'], [21, '6', '10', '5'], [21, '8', '7', '6'], [21, '3', '9', '9'], [20, '7', '7', '6'], [20, '10', '7', '3'], [20, '10', '8', '2']]

I want to read each value and write to a file. I am having an issue converting the first value to a string

Here is my code:

with open('problem2.txt', 'w') as writer:
for list in sortedLines:
    string=''
    for i in list:
        if list.index(i) == 0:
            string = str(i)   ": "
            print(type(i))
        else:
            string= string   " "   i
    writer.writelines(string "\n")

The type(i) returns <int>. I get the following error - TypeError: 'str' object is not callable

CodePudding user response:

You could use a format string and let Python worry about the conversion:

for list in sortedLines
  string = '{list[0]}: {" ".join(list[1:]}\n' 
  writer.writelines(string)

This should produce lines of the format:

30: 10 10 10
27: 10 10 7
27: 9 8 10
25: 9 9 7
25: 7 10 8

CodePudding user response:

There is 1 main issue that I could find: you have called 'list' in your range. This is already a built-in name, and you are overriding it. Instead, I suggest calling it line.

This worked for me:

with open('problem2.txt', 'w') as writer:
    for line in sortedLines:
        string = str(line[0])   ": "
        for i in line[1:]:
            string  = " "   i
        writer.writelines(string   "\n")

I removed the if-else, just because it was unnecessary and the same effect could be achieved when defining the string.

  • Related