Home > Software engineering >  Get the UTF-8 code of a character in Python or shell
Get the UTF-8 code of a character in Python or shell

Time:01-06

How can I get the UTF-8 code of a single character in Python or in the shell?

I’d like to have (see here for distinguishing between "plus" and "full plus" signs):

getUTF8('+')
> U FF0B
getUTF8(' ')
> U 002B

CodePudding user response:

I came up with this:

def getUTF8(c):
   return "U {:04x}".format(ord(c)).upper()

With above example:

for c in ['+', ' ']:
   print(getUTF8(c))

> U FF0B
> U 002B

CodePudding user response:

Using bash, zsh or ksh93 with a UTF-8 aware locale:

$ printf "U X\n" "'+" "' "
U FF0B
U 002B

When their builtin versions of printf(1) see a numeric format specifier (Like %X), and the first character of the relevant argument (After the usual shell wordsplitting and parsing) is a double or single quote, the next character's codepoint value is taken as the argument, instead of the character itself.

  •  Tags:  
  • Related