The ascii()
function is one of Python's built-in functions that converts an object to its ASCII string representation.
Specifically, if the object is a string containing ASCII printable characters, spaces, or ASCII escape characters, ascii()
returns the string's literal representation. Otherwise, it generates an ASCII string representation of the object using syntax similar to Python 2.x's repr()
function.
Example Code
print(ascii("Hello, world!")) # Output: "'Hello, world!'"
print(ascii("你好,世界!")) # Output: "'\\u4f60\\u597d\\uff0c\\u4e16\\u754c\\uff01'"
print(ascii(123)) # Output: '123'
print(ascii("\x80")) # Output: "'\\x80'"
In the examples above:
- The first string can be represented as an ASCII string, so
ascii()
returns its literal representation; - The second string contains non-ASCII characters, so
ascii()
represents it using Unicode escape sequences; - The third example is an integer, which is converted to its corresponding ASCII string;
- The last example contains a non-ASCII character, which is converted to an ASCII string with escape characters.