Peter Otten wrote: > 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'
There is also the from __future__ import unicode_literals directive in Python 2.7. With that "..." will be unicode, and bytestrings must be marked b"...". The latter is understood by both 2.7 and 3.x _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor