Alignment with string.format and Unicode

Asked

Viewed 4,176 times

5

I’m having trouble with the alignment of strings when using the .format(), for example when doing:

>>> print '{:>6}'.format('agua'}
  agua

>>> print '{:>6}'.format('água'}
 água

Note that the first format goes out as expected, 2 spaces + 4 characters = 6. In the second it does not happen, it was 1 space + 4 characters, because the size of this string Unicode is larger than we visually see

>>> len('agua')
4
>>> len('água')
5

This is 'breaking' all the alignment of my output, there is some way to fix it?

1 answer

2


Python 2.x, use the prefix u to represent the string as Unicode:

>>> print '{:>6}'.format('agua')
  agua
>>> print u'{:>6}'.format(u'água')
  água
>>> 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.