Use ascii in python

Python ascii() Method

ASCII stands for American Standard Code for Information Interchange. It is a character encoding standard that uses numbers from 0 to 127 to represent English characters. For example, ASCII code for the character A is 65, and 90 is for Z. Similarly, ASCII code 97 is for a, and 122 is for z. ASCII codes are also used to represent characters such as tab, form feed, carriage return, and also some symbols.

The ascii() method in Python returns a string containing a printable representation of an object for non-alphabets or invisible characters such as tab, carriage return, form feed, etc. It escapes the non-ASCII characters in the string using \x , \u or \U escapes.

Syntax:

Parameters:

object: Any type of object.

Return type:

The ascii() method returns a printable carriage return character in a string, as shown below.

mystr='''this is a new line.''' print(ascii(mystr)) 

In the above example, mystr points to a string with a carriage return, which takes a string in the new line. It is an invisible character in the string. The ascii() method returns a printable string that converts a carriage return to printable char \n. Please note that it does not convert other English characters.

Читайте также:  Javascript and html elements

The following example prints symbol Ø using the ascii() method:

NormalText = "A string in python." SpecialText = "A string in pythØn." print(ascii(NormalText)) print(ascii(SpecialText)) 
'A string in python.' 'A string in pyth\xd8n.' 

In the above example, ASCII code for Ø is decimal 216, and hexadecimal D8, which is represented using \x prefix, \xd8. So, the ascii() method converts Ø to \xd8 in a string.

It escapes the non-ASCII characters in the string using \x , \u or \U escapes.

The following demonstrates the ascii() method with lists.

Languages = ['pythØn','C++','Go'] print(ascii(Languages)) 

Источник

ASCII value in Python

There are many languages and hence an unlimited number of symbols in this world. All the symbols are represented in a computer using different types of encoding such as ASCII and Unicode. In this article, we will see how we can find the ASCII value of a given character in Python.

What is the ASCII value?

ASCII stands for “American Standard Code For Information Interchange”. It contains only 128 characters that are used to represent different symbols, decimal digits and English alphabets in a computer.

In the ASCII encoding, each character has been assigned a numeric value between 0 to 127. This numeric value associated to a character is called the ASCII value of the character.

  • “A” has been assigned the ASCII value 65. All the uppercase letters have been assigned the ASCII values after 65 in their respective order. i.e. “B” has an ASCII value of 66, “C” has an ASCII value of 67, and so on.
  • “a” has been assigned the ASCII value 97. All the lowercase letters have been assigned the ASCII values after 97 in their respective order. i.e. “b” has an ASCII value of 98, “c” has an ASCII value of 99, and so on.

How to print the ASCII value of a character in Python?

To print the ASCII value of a given character, we can use the ord() function in python. The ord() function takes the given character as input and returns the ASCII value of the character. You can observe this in the following example.

char1 = "A" result1 = ord(char1) print("ASCII value of the character <> is <>.".format(char1, result1)) char2 = "B" result2 = ord(char2) print("ASCII value of the character <> is <>.".format(char2, result2)) char3 = "C" result3 = ord(char3) print("ASCII value of the character <> is <>.".format(char3, result3)) char4 = "Z" result4 = ord(char4) print("ASCII value of the character <> is <>.".format(char4, result4)) char5 = "a" result5 = ord(char5) print("ASCII value of the character <> is <>.".format(char5, result5)) char6 = "b" result6 = ord(char6) print("ASCII value of the character <> is <>.".format(char6, result6)) char7 = "c" result7 = ord(char7) print("ASCII value of the character <> is <>.".format(char7, result7)) char8 = "z" result8 = ord(char8) print("ASCII value of the character <> is <>.".format(char8, result8))
ASCII value of the character A is 65. ASCII value of the character B is 66. ASCII value of the character C is 67. ASCII value of the character Z is 90. ASCII value of the character a is 97. ASCII value of the character b is 98. ASCII value of the character c is 99. ASCII value of the character z is 122.

If we pass a value other than a character to the ord() function, it will raise a TypeError exception. For example, if we pass a string containing multiple characters instead of a single character, the ord() function will raise TypeError as follows.

char1 = "ABC" result1 = ord(char1) print("ASCII value of the character <> is <>.".format(char1, result1))
Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in result1 = ord(char1) TypeError: ord() expected a character, but string of length 3 found

Similarly, if we pass an integer instead of a character to the ord() function, it will raise the TypeError exception as follows.

num1 = 123 result1 = ord(num1) print("ASCII value of the character <> is <>.".format(num1, result1))
Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in result1 = ord(num1) TypeError: ord() expected string of length 1, but int found 

Conclusion

In this article, we have discussed the ASCII encoding. We also saw how we can find the ASCII value of a character in Python. To know more about different values and allowed characters in python, you can read these articles on python literals and data types in python.

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Источник

How to use the Python ascii() function

Python Ascii

In this article, we’ll take a look at the Python ascii() function.

The ascii() function returns a string representation of the object but only having ASCII characters as it is.

The remaining non-ASCII characters will be escaped with a backslash (\). For example, the newline character ( \n ) is a non-ASCII character.

We’ll now look at some examples to understand how it exactly works!

Using the Python ascii() function – Some examples

The Python ascii() function takes a single argument, which can be any object. So all kinds of objects, like lists, strings, etc, are valid. This will return a string.

If you’re using it on a List, or any collection, this function will get called for each member of the collection.

Let’s take a look at this now.

Using Python ascii() on primitive datatypes

For basic datatypes like boolean , string , int , they work as you expect.

i = 15 print(ascii(i)) b = True print(ascii(b)) s = 'abc' print(ascii(s)) s = 'Hello from\tAskPython\n' print(ascii(s))
'15' 'True' "'abc'" "'Hello from\\tAskPython\\n'"

As you can see, for the non-ASCII characters (\t, \n), the backslash itself needs to be escaped.

Using ascii() on Iterables/Collections

In case you want to use it on a list/tuple/dictionary, you still can! But, this will simply apply it to every member in the collection/iterable.

So if a list has n elements, we’ll get the function applied to all n of them, and get back a list of strings.

m = ["Hello from AskPython 22", "AskPythön", "Hi"] print(ascii(m))
['Hello from AskPython 22', 'AskPyth\xf6n', 'Hi']

Similarly, with a Dictionary < key : value >, it’ll be applied to both key and value .

For a tuple, it is similar to that of a list. All elements will be converted to a string representation of ASCII-like characters.

t = ("Hellö", 123, ["AskPython"]) print(ascii(t))

Comparison with the repr() function

The repr() function is also used to return a string representation of objects. But the difference is that repr() prints the non-ascii characters as such.

For custom objects, the ascii() function internally calls the __repr__() function, but makes sure to escape non-ASCII characters.

Let’s experiment with this, by creating our own object, using a class.

class MyClass: def __init__(self, name): self.name = name

Now, let’s create an object and try to invoke ascii() and repr() on it,

my_obj = MyClass("AskPythön") print(ascii(my_obj)) print(repr(my_obj))

We don’t have a repr() function for this class, so the default object definition is used. That’s why you see MyClass object in the output.

To change this, we must overload the __repr__() dunder method ourselves.

class MyClass: def __init__(self, name): self.name = name def __repr__(self): return self.name

Now, when you invoke ascii() or repr() , we can directly get the name attribute!

my_obj = MyClass("AskPythön") print(ascii(my_obj)) print(repr(my_obj))

Now, you can clearly see the difference!

Conclusion

In this article, we learned about using the ascii() function in Python and learned to use it on different types of objects.

References

Источник

Оцените статью