Python Forum
Zfill Method Parameter Confusion
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Zfill Method Parameter Confusion
#1
Hello,

I was going through a tutorial on Unicode and character encodings in Python and I came across a function that the author presents as a way to convert Unicode strings that look like "U+10346" into actual Unicode characters. The function is as follows:

def make_uchr(code: str):
     return chr(int(code.lstrip("U+").zfill(8), 16))
I'm having trouble understanding why there are two numbers as parameters after ".zfill." Everything I read online says that .zfill only takes one parameter (the specified length of the zero-filled string that is sought) and I don't believe the "16" is an argument that is used by the lstrip method. If anyone could help clarify this for me I'd greatly appreciate it. Thank you.
Reply
#2
16 is a second argument to int(). It is assumed that the string contains hexadecimal characters and it is converted to int in base 16. For example
>>> int("000002A3", 16)
675
>>> chr(int("000002A3", 16))
'ĘŁ'
>>> '\N{LATIN SMALL LETTER DZ DIGRAPH}'
'ĘŁ'
for the character 'LATIN SMALL LETTER DZ DIGRAPH'
Reply
#3
Can drop filling in zeros and it will still work.
>>> chr(int(u.lstrip("U+"), 16))
'𐍆'

>>> u = 'U+1F496'
>>> chr(int(u.lstrip("U+"), 16))
'💖'

>>> u = 'U+1F47D'
>>> chr(int(u.lstrip("U+"), 16))
'👽'

>>> u = "U+1f4af"
>>> chr(int(u.lstrip("U+"), 16))
'💯'

>>> u = 'U+1F389'
>>> chr(int(u.lstrip("U+"), 16))
'🎉'

# Using name
>>> '\N{Party Popper}'
'🎉'
Reply
#4
Thank you both!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  zfill prints extra et the end of a var tester_V 4 850 Mar-24-2023, 06:59 PM
Last Post: tester_V
  [ERROR] ParamValidationError: Parameter validation failed: Invalid type for parameter gdbengo 3 10,654 Dec-26-2022, 08:48 AM
Last Post: ibreeden
  sqlite3 question - execute method with :parameter richalt2 2 7,371 May-20-2019, 05:35 PM
Last Post: woooee
  Input as not default method parameter dan789 4 2,861 Mar-08-2019, 09:04 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020