views:

64

answers:

3

This piece of code is supposed to go through a list and preform some formatting to the items, such as removing quotations, and then saving it to another list.

class process:
    def rchr(string_i, asciivalue):
        string_o = ()
        for i in range(len(string_i)):
            if ord(string_i[i]) != asciivalue:
                string_o += string_i[i]
        return string_o
    def flist(self, list_i):
        cache = ()
        cache_list = []
        index = 0
        for line in list_i:
            cache = line.split('\t')
            cache[0] = process.rchr(str(cache[0]), 34)
            cache_list.append(cache[0])
            cache_list[index] = cache
            index += 1
        cache_list.sort()
        return cache_list

p = process()
list1a = ['cow', 'dog', 'sheep']
list1 = p.flist(list1a)
print (list1)

However; it chokes at string_o += string_i[i] and gives the following error:

Traceback (most recent call last):
  File "/Projects/Python/safafa.py", line 23, in <module>
    list1 = p.flist(list1a)
  File "/Projects/Python/safafa.py", line 14, in flist
    cacbe[0] = process.rchr(str(cache[0]), 34)
  File "/Projects/Python/safafa.py", line 7, in rchr
    string_o += string_i[i]
TypeError: can only concatenate tuple (not "str") to tuple
+3  A: 

I think you want string_o = "" instead of string_o = ()

Your problem is that you want string_o to be a string so you can append other strings onto it. Setting it equal to () makes it a tuple instead, which is a data type incompatible with string.

Gabe
why does "" make it work and () doesn't?
Protean
@Protean Because a tuple (,) cannot be modified. A list [] can. Why have a tuple type then? Because a tuple can be used as a dict _key_ because it's immutable (unmodifiable), and a list can be modified and thus cannot be used as dict keys.
extraneon
@gabe wouldn't string_o = [] and at the end "".join(string_o) be better? Otherwise Python is creating and discarding strings all the time.
extraneon
extraneon: `replace('"', '')` would be even better than the whole rchr function, but the poster wanted to know why his code wouldn't work, not how to make it better. As a beginner, he needs to learn programming before Python idioms.
Gabe
+3  A: 

In addition to the previous answer, a more pythonic way to go would be:

string_o = ''.join(c for c in string_i if ord(c) != asciivalue)

It is short and readable.

Olivier
+2  A: 

To add to Olivier's answer, I think the whole code could be replaced with:

import itertools
output  = [i.replace('"','') for i in list(itertools.chain(*(x.split('\t') for x in input)))]

Tested with python 2.x only.

Kimvais