Hello,
The reason for this behavior is inconsistency in Python 2 related to
how it handles constructing strings from byte strings and Unicode
strings. In most cases such operations produce Unicode strings:
>>> 'foo' + u'bar'
u'foobar'
>>> 'foo' + u'\xe4'
u'foo\xe4'
>>> '%s' % u'foo'
u'foo'
>>> '%s' % u'\xe4'
u'\xe4'
As seen above, it's OK that the Unicode string contains non-ASCII
characters. If the byte string contains non-ASCII characters, you get
an error:
>>> '\xe4' + u'foo'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in
position 0: ordinal not in range(128)
>>> '\xe4 %s' % u'foo'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in
position 0: ordinal not in range(128)
In other words, you can use the old string formatting with Unicode
strings being inserted into the template as long as the template
itself is pure ASCII. As a result you get an Unicode string.
Unfortunately the new string formatting system doesn't work like that.
The outcome of the `template.format()` depends on is the template a
byte string or a Unicode string:
>>> '{}'.format('foo')
'foo'
>>> '{}'.format(u'foo')
'foo'
>>> u'{}'.format('foo')
u'foo'
As seen above, inserted Unicode strings are converted to byte strings
if the template is a byte strings. This obviously fails if inserted
strings contain non-ASCII characters:
>>> '{}'.format(u'\xe4')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4'
in position 0: ordinal not in range(128)
A workaround is using Unicode strings in templates:
>>> u'{}'.format(u'\xe4')
u'\xe4'
An alternative solution is just using the old string formatting
syntax. It's not deprecated nor going to be deprecated in the future.
Cheers,
.peke
> --
> You received this message because you are subscribed to the Google Groups
> "robotframework-users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to
robotframework-u...@googlegroups.com.
> To post to this group, send email to
robotframe...@googlegroups.com.
> Visit this group at
https://groups.google.com/group/robotframework-users.
> For more options, visit
https://groups.google.com/d/optout.
--
Agile Tester/Developer/Consultant ::
http://eliga.fi
Lead Developer of Robot Framework ::
http://robotframework.org