9

I got the following error:

 Second line.
Traceback (most recent call last):
  File "./main.py", line 8, in <module>
    print >>output, u'Second line.'
TypeError: unicode argument expected, got 'str'

When I run the following code. I don't know what is wrong. Could anybody show me how to fix it?

#!/usr/bin/env python
# vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:

import io
output = io.StringIO()
output.write(u'First line.\n')
print u'Second line.'
print >>output, u'Second line.'
contents = output.getvalue()
print contents
output.close()
martineau
  • 119,623
  • 25
  • 170
  • 301
user1424739
  • 11,937
  • 17
  • 63
  • 152

1 Answers1

11

For Python 2 consider using the StringIO module instead of io.

Code:

from StringIO import StringIO

Test Code:

from StringIO import StringIO
output = StringIO()
output.write(u'First line.\n')
print u'Second line.'
print >>output, u'Second line.'
contents = output.getvalue()
print contents
output.close()

Results:

Second line.
First line.
Second line.
martineau
  • 119,623
  • 25
  • 170
  • 301
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • You meant `print contents.encode('utf-8')` since contents is of the type `unicode`? Also, `io.StringIO` is available in python2, when it instead of `StringIO.StringIO` should be used? – user1424739 Jun 03 '18 at 15:11
  • 2
    io is available but it is a back port from Python 3. Evidently print redirection confuses it. You are using Python2 only features, so the StringIO module could be fine to use. – Stephen Rauch Jun 03 '18 at 15:25
  • 1
    if you want to use the backported `io.StringIO` you should also be using the backported `print` with `from __future__ import print_function` – avigil Jun 03 '18 at 15:54