Welcome to the Pycom forum Forum
    • \[\[global:header.categories\]\]
    • \[\[global:header.recent\]\]
    • \[\[global:header.tags\]\]
    • \[\[global:header.popular\]\]
    • Login

    Explore Pybytes | Official Documentation | Report a Firmware Bug/Issue | GitHub

    utf-8 iteration / ord() behaves unexpected

    Scheduled Pinned Locked Moved WiPy 2&3
    2 Posts 1 Posters 167 Views 1 Watching
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • P Offline
      Peter Ehses
      last edited by Peter Ehses

      Hi, I'm trying to iterate over a string containing German Umlaute (äöü) to get the matching unicode position as Decimal.

      It's working for single characters

      print(ord(b'ä'))
      print(ord(bytes('ä', "utf-8")))
      

      outputs

      228
      228

      It doesn't, however, work once I iterate over the characters.

      text = "aldköäü"
      for index in range(len(text)):
          char = text[index]
          print("char:")
          print(char)
          print(char.encode("utf-8"))
          print(ord(bytes(char, "utf-8")))
      

      outputs

      char:
      a
      b'a'
      97
      char:
      l
      b'l'
      108
      char:
      d
      b'd'
      100
      char:
      k
      b'k'
      107
      char:
      ���
      b'\xf6\xe4\xfc\x00'
      Traceback (most recent call last):

      File "<stdin>", line 52, in <module>

      TypeError: ord() expected a character, but string of length 4 found

      How can I get this to work? I'm using a WiPy 3.0 and plan to use the same code on a GPy

      1 Reply Last reply Reply Quote 0
      • P Offline
        Peter Ehses
        last edited by

        For future reference: Here's a solution.

        text = "aouäöü"
        
        print(text)
        print(len(text))
        
        for char in text:
            print(char)
            print(ord(bytes(char, "utf-8")))
        
        1 Reply Last reply Reply Quote 0

        Hello! It looks like you're interested in this conversation, but you don't have an account yet.

        Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.

        With your input, this post could be even better 💗

        Register Login
        • 1 / 1
        • First post
          Last post

        Pycom on Twitter

        Pycom