开发者

Why do I get a parentheses when writing text to a file?

for node in tree.getiterator('TARGET'):
    tgt_name = node.attri开发者_运维百科b.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?


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))


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']))


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


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜