[Tutor] trouble with stringio function in python 3.2
Peter Otten
__peter__ at web.de
Mon May 4 09:53:16 CEST 2015
anupama srinivas murthy wrote:
> Hello,
>
> My python code needs to run on versions 2.7 to 3.4. To use stringio
> function as appropriate, the code i use is;
>
> if sys.version < '3':
> dictionary = io.StringIO(u"""\n""".join(english_words))
> else:
> dictionary = io.StringIO("""\n""".join(english_words))
>
> The code runs fine on all versions mentioned above except for 3.2 where i
> get the error:
> dictionary = io.StringIO(u"""\n""".join(english_words))
> ^
> SyntaxError: invalid syntax
>
> How can I solve the issue?
Unfortunately Python 3.2 doesn't understand the u-prefixed syntax for
unicode strings. Are the strings in english_words all unicode? Then
dictionary = io.StringIO("\n".join(english_words))
should work. In Python 3 "\n" is unicode anyway, and Python 2 implicitly
converts "\n" to unicode:
$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "\n".join([u"foo", u"bar"])
u'foo\nbar'
More information about the Tutor
mailing list