Free cookie consent management tool by TermsFeed The upper() method of bytearray class in Python | Pythontic.com

The upper() method of bytearray class in Python

Overview: 

  • The upper() method of the bytearray class creates a new bytearray consisting of uppercase ASCII characters from a bytearray of lowercase ASCII characters. Since the bytearray is a sequence of bytes only ASCII characters are allowed in a bytearray object. 
  • Passing of Unicode characters while creating a bytearray will lead Python to issue an error stating, “SyntaxError: bytes can only contain ASCII literal characters”

The upper() method of bytearray class in Python

  • A bytearray is a mutable sequence of bytes and the method upper() works for the ASCII range of characters. For converting a sequence of Unicode characters e.g., Russian alphabets to uppercase, the upper() method of Python str class can be used. A Python string is an immutable sequence of Unicode characters.

Example:

# Example Python program that creates a 
# bytearray consisting of uppercase ASCII 
# characters from the lowercase ones  

# A bytearray with lowercase characters
bufferLowerCase = bytearray(b"cheshire cat")
print("The bytearray in lowercase:")
print(bufferLowerCase)
print(id(bufferLowerCase))

# A bytearray with uppercase characters
bufferUpperCase = bufferLowerCase.upper()
print("The bytearray in uppercase:")
print(bufferUpperCase)
print(id(bufferUpperCase))

Output:

The bytearray in lowercase:
bytearray(b'cheshire cat')
4344445104
The bytearray in uppercase:
bytearray(b'CHESHIRE CAT')
4344445040

 


Copyright 2025 © pythontic.com