In the world of programming, ASCII and Strings Datas have utmost importance. ASCII (American Standard Code for Information Interchange) is a standard that assigns letters, numbers, and other characters within the 256 slots available in the 8-bit code.
It helps humans use machines more efficiently. In this tutorial, we’ll focus on how you can convert a string to its ASCII value in the Python programming language.
Install Python
First, you’ll need Python installed on your computer. Python 3.x is recommended. If you haven’t installed Python yet, you can get it from the official site.
Know Your Tools: Python’s ord() Function
To convert a specific string character to its equivalent ASCII value, Python provides a built-in function called ord(). You simply put your desired character inside this function to get its ASCII value.
Here’s an example:
1 2 |
my_char = 'A' print(ord(my_char)) |
The ord() function will return the ASCII value of ‘A’, which is 65.
65
String to ASCII: Going through string character by character
If you have a string of multiple characters, you can use a for loop in Python to go through each character and convert them individually to ASCII. Let’s use the string “Hello” as an example:
1 2 3 |
my_str = 'Hello' for char in my_str: print(char, " : ", ord(char)) |
The output will be:
H : 72 e : 101 l : 108 l : 108 o : 111
The Full Code
1 2 3 4 5 6 7 8 |
#sample character my_char = 'A' print(ord(my_char)) #sample string and converting each character into ASCII my_str = 'Hello' for char in my_str: print(char, " : ", ord(char)) |
Conclusion
In this tutorial, we have walked through converting a string to its ASCII value in Python by using the Python’s built-in ord() function, and a for loop to handle strings of multiple characters. I hope this guide was helpful in expanding your Python knowledge.