0

i am trying to format a bunch of strings in python 2.7.6. Everything works properly until an unicode sign shows up. This short example shows my problem:

    a = 'ö'
    b = 'd'
    c = 'e'

    print('{:2}{:2}{:2}').format(a, b, c)

The result is:

öd e

But it should be:

ö d e

Tried a lot of stuff with encoding, decoding, unicodedata.normalize, but nothing seems to work. Anyone got an idea what i am doing wrong? Thanks for help and please excuse for my bad english. Greetz,

BigZ

4
  • I bet this has something to do with the fact that len(a) is 2, even though it looks like it's only one character long. Commented Sep 30, 2014 at 13:46
  • Works fine for me on 2.7.6 - note that your parentheses are a bit wayward, but don't really change the syntax. Commented Sep 30, 2014 at 13:54
  • Decoding the letter into utf-8 will make len(a) show a length of 1, but if i try this in my code it throws an UnicodeDecodeError if an unicode sign shows up :/ Commented Sep 30, 2014 at 13:55
  • Just discovered that im using 2.7.6 too 0:) Commented Sep 30, 2014 at 13:57

1 Answer 1

1

Does this do the trick for you?

>>> a = 'ö'
>>> b = 'd'
>>> c = 'e'
>>> print(u'{:2}{:2}{:2}'.format(a.decode('utf8'), b, c))
ö d e

This assumes that your data is utf8 encoded. Note that the format string is unicode.

Also, this doesn't seem to be a problem in Python 3.

Sign up to request clarification or add additional context in comments.

7 Comments

Nope, sorry. This works fine in the example, but in my code it throws a UnicodeDecode Exception. :/
@BigZ You have a fundamental problem in that you're storing encoded data as bytes and wanting Python to know what it is.
So how do i get python to store my encoded data as strings?
It's hard to tell without knowing what you're doing, but you'll want to use unicode for text.
Just discovered that im getting unicode and strings in my code, while parsing html and printing the results... -.- Is there a way to unify everything?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.