Reputation: 11
for node in tree.getiterator('TARGET'):
tgt_name = node.attrib.get('NAME')
print map_name, ",", "TARGET" , ", " , tgt_name
tgt_name_str = map_name, ",", "TARGET" , ", " , tgt_name
writer.writelines (str(tgt_name_str))
writer.writelines('\n')
Here is the output file content:
('m_myname', ',', 'TARGET', ', ', 'mytable')
In the above the parentheses is also written as part of the text file, but I don't that. Any idea how to remove this parentheses getting written to a file?
Upvotes: 1
Views: 1698
Reputation: 7788
tgt_name_str = map_name, ",", "TARGET" , ", " , tgt_name
creates a tuple, the string representation of which is surrounded by parenthesis.
Others have suggested ''.join([map_name, ",", "TARGET" , ", " , tgt_name])
, but you could do ', '.join([map_name, "TARGET", tgt_name])
. The join will put the ', ' in between the elements of the supplied array. Note that this may differ from your desired output as in your code, there's no space after the first comma but there is after the second. Is that intentional?
Upvotes: 0
Reputation: 9469
If you assign multiple values to a single variable, as in:
tgt_name_str = map_name, ",", "TARGET" , ", " , tgt_name
Python will implicitly convert that into a tuple. It's equivalent to writing:
tgt_name_str = (map_name, ",", "TARGET" , ", " , tgt_name)
and so that is what str(tgt_name_str) supplies.
You might want to concatenate the values:
tgt_name_str = map_name + "," + "TARGET" + ", " + tgt_name
, use ''.join or create your own format template to get the output you desire.
Upvotes: 0
Reputation: 10592
because tgt_name_str = map_name, ",", "TARGET" , ", " , tgt_name
is a tuple.
replace by:
tgt_name_str = ''.join([map_name, ",", "TARGET" , ", " , tgt_name])
# or
tgt_name_str = map_name + "," + "TARGET" + ", " + tgt_name
Upvotes: 0
Reputation: 76856
This line:
tgt_name_str = map_name, ",", "TARGET" , ", " , tgt_name
creates a tuple, and the string representation of a tuple is enclosed in parenthesis. To do what you want, use this:
writer.write("{0}, TARGET, {1}\n".format(map_name, tgt_name))
Upvotes: 2
Reputation: 29121
This is because when you execute next line:
tgt_name_str = map_name, ",", "TARGET" , ", " , tgt_name
tgt_name_str will contain a tuple, so when you call str(tgt_name_str) it gives you data with paranthesis.
To check this you can simply add statement with print type(tgt_name_str).
So to fix it you can use join:
tgt_name_str = ''.join([map_name, ",", "TARGET" , ", " , tgt_name])
OR:
for node in tree.getiterator('TARGET'):
tgt_name = node.attrib.get('NAME')
writer.writelines (''.join([map_name, ",", "TARGET" , ", " , tgt_name, '\n']))
Upvotes: 1