I have a string ë́aúlt that I want to get the length of a manipulate based on character positions and so on. The problem is that the first ë́ is being counted twice, or I guess ë is in position 0 and ´ is in position 1.
Is there any possible way in Python to have a character like ë́ be represented as 1?
I’m using UTF-8 encoding for the actual code and web page it is being outputted to.
edit: Just some background on why I need to do this. I am working on a project that translates English to Seneca (a form of Native American language) and ë́ shows up quite a bit. Some rewrite rules for certain words require knowledge of letter position (itself and surrounding letters) and other characteristics, such as accents and other diacritic markings.
UTF-8 is an unicode encoding which uses more than one byte for special characters. If you don’t want the length of the encoded string, simple decode it and use
len()on theunicodeobject (and not thestrobject!).Here are some examples:
Of course, you can also access single characters in an
unicodeobject like you would do in astrobject (they are both inheriting frombasestringand therefore have the same methods):If you develop localized applications, it’s generally a good idea to use only
unicode-objects internally, by decoding all inputs you get. After the work is done, you can encode the result again as ‘UTF-8’. If you keep to this principle, you will never see your server crashing because of any internalUnicodeDecodeErrors you might get otherwise 😉PS: Please note, that the
strandunicodedatatype have changed significantly in Python 3. In Python 3 there are only unicode strings and plain byte strings which can’t be mixed anymore. That should help to avoid common pitfalls with unicode handling…Regards,
Christoph