Pygame: Is there any easy way to find the letter/number of ANY alphanumeric pressed?

There a basically two ways:

Option 1: use pygame.key.name().

It's as simple as

for event in pygame.event.get():
  if event.type == pygame.KEYDOWN:
    print(pygame.key.name(event.key))

The advantage over using chr is that chr works only if the value of event.key is between 0 and 255 (inclusive).

If you press menu, Alt Gr, Tab or LShift, pygame.key.name will happily return menu, alt gr, tab and left shift, while chr will crash, crash, return whitespace, and crash.


Option 2: use the unicode attribute of the pygame.KEYDOWN event

for event in pygame.event.get():
  if event.type == pygame.KEYDOWN:
    print(event.unicode)

It will get you the letter/number or an empty string when using a function key, and it will also take modifiers into account, e.g. if you hold Shift while pressing a it will return A instead of just a.

The pygame.KEYDOWN event has additional attributes unicode and scancode. unicode represents a single character string that is the fully translated character entered. This takes into account the shift and composition keys. scancode represents the platform-specific key code.


if you look K_a is just 97 thats the ascii code for 'a' , I will extrapolate to K_? is the ascii code for whatever the question mark represents

if event.type == KEYUP: 
    print chr(event.key) #convert ascii code to a character

maybe?

as pointed out this will not work with ascii over 255 (no longer ascii really)

you can use the method outlined below or just use unichr(event.key) instead of chr