Python convert string to ascii

ASCII string converting in Python

In this tutorial, we will learn how to convert between ASCII values and characters in Python.

To convert a character to its corresponding ASCII value, you can use the built-in ord() function. The ord() function takes a single character string as input and returns its Unicode code point, which is the same as the ASCII value for characters in the ASCII table.

# Convert a character to its ASCII value char = 'A' ascii_value = ord(char) print(f"The ASCII value of is ")
The ASCII value of A is 65

To convert an ASCII value to the corresponding character, you can use the built-in chr() function. The chr() function takes an integer (the Unicode code point) as input and returns the corresponding character.

# Convert an ASCII value to a character ascii_value = 65 char = chr(ascii_value) print(f"The character corresponding to the ASCII value is ")
The character corresponding to the ASCII value 65 is A

To convert a string of characters to a list of ASCII values, you can use a list comprehension along with the ord() function.

input_string = "Hello" # Convert the string to a list of ASCII values ascii_values = [ord(char) for char in input_string] print(f"The ASCII values of the string '' are ")
The ASCII values of the string 'Hello' are [72, 101, 108, 108, 111]

To convert a list of ASCII values to a string, you can use a list comprehension along with the chr() function and then join the characters using the join() method.

ascii_values = [72, 101, 108, 108, 111] # Convert the list of ASCII values to a string output_string = ''.join([chr(value) for value in ascii_values]) print(f"The string corresponding to the ASCII values is ''")
The string corresponding to the ASCII values [72, 101, 108, 108, 111] is 'Hello'

In this tutorial, we learned how to convert between characters and their ASCII values, and how to convert entire strings to and from lists of ASCII values in Python.

Источник

Convert String to ASCII Value in Python

Convert String to ASCII Value in Python

  1. Use the for Loop Along With the ord() Function to Get ASCII of a String in Python
  2. Use the List Comprehension and the ord() Function to Get ASCII of a String in Python
  3. Use a User-Defined Function to_ascii() to Get ASCII of a String in Python

This tutorial will introduce some methods to convert a string into ASCII values in Python.

Use the for Loop Along With the ord() Function to Get ASCII of a String in Python

We can use the for loop and the ord() function to get the ASCII value of the string. The ord() function returns the Unicode of the passed string. It accepts 1 as the length of the string. A for loop is used for iterating over a sequence: a list, a tuple, a dictionary, a set, or a string. Therefore, we can use the for loop to parse every character of the string and convert it into ASCII values.

Читайте также:  Ошибка при выделении памяти java

In the code below, text is a variable that holds the user input. ascii_values is an empty list initially, which will hold the ASCII values of each character in the string later. Once the loop has completed its cycle, we will display the contents of ascii_values as output to the user. The append() function adds a new item to the list ascii_values after each iteration.

When we run this program user is prompted with a string, and once the user provides a string, it will be stored in a variable text . In the example, the input is the string hello . The ASCII value of each character of the string is printed.

#python 3.x text = input("enter a string to convert into ascii values:") ascii_values = [] for character in text:  ascii_values.append(ord(character)) print(ascii_values) 
enter a string to convert into ASCII values: hello [104, 101, 108, 108, 111] 

Use the List Comprehension and the ord() Function to Get ASCII of a String in Python

We can use the list comprehension to achieve the same result. The list comprehension in Python is an easy and compact syntax for creating a list from a string or another list. It is a concise way to create a new list by operating on each item in the existing list. The list comprehension is considerably faster than processing a list using the for a loop.

In the code below, there is no for or while loop externally. But within list comprehension, we are using for loop to get each character of the text .

#python 3.x text = input("enter a string to convert into ascii values: ") ascii_values = [ord(character) for character in text] print(ascii_values) 
enter a string to convert into ASCII values: hello [104, 101, 108, 108, 111] 

Use a User-Defined Function to_ascii() to Get ASCII of a String in Python

Another way of writing the code to accomplish the same goal is to use a user-defined function. User-defined functions are functions that you use to organize your code in the body of a policy. Once you define a function, you can call it similar to the built-in action and parser functions. Variables that are passed to a function are passed by reference rather than by value.

In the code below, we use a user-defined function to_ascii to take text as a parameter. Inside the function, block operation is defined, and the result is transferred by keyword return . When the function to_ascii is called from the main module providing text as parameter control transfers to the to_ascii function and code block is executed, we get ASCII values of the given string in a list.

#python 3.x def to_ascii(text):  ascii_values = [ord(character) for character in text]  return ascii_values text = input("Enter a string: ") print(to_ascii(text)) 
Enter a string: hello [104, 101, 108, 108, 111] 

Related Article — Python ASCII

Источник

Читайте также:  Modules in java are called

Convert string to ASCII value python

How would you convert a string to ASCII values? For example, «hi» would return [104 105] . I can individually do ord(‘h’) and ord(‘i’), but it’s going to be troublesome when there are a lot of letters.

9 Answers 9

You can use a list comprehension:

>>> s = 'hi' >>> [ord(c) for c in s] [104, 105] 

Here is a pretty concise way to perform the concatenation:

>>> s = "hello world" >>> ''.join(str(ord(c)) for c in s) '10410110810811132119111114108100' 

And a sort of fun alternative:

>>> '%d'*len(s) % tuple(map(ord, s)) '10410110810811132119111114108100' 

What was I thinking? This is much more pythonic than mine. That’s what I get for trying to answer a python question right after reading a bunch of Haskell questions. +1

In 2021 we can assume only Python 3 is relevant, so.

>>> list(b"Hello") [72, 101, 108, 108, 111] 
>>> list("Hello".encode('ascii')) [72, 101, 108, 108, 111] 

If you want a single solution that works with both:

(all the above will intentionally raise UnicodeEncodeError if str contains non-ASCII chars. A fair assumption as it makes no sense to ask for the «ASCII value» of non-ASCII chars.)

If you are using python 3 or above,

>>> list(bytes(b'test')) [116, 101, 115, 116] 

A great approach, but bytes() is redundant for a bytes input, and for a string input you need to specify an encoding.

If you want your result concatenated, as you show in your question, you could try something like:

>>> reduce(lambda x, y: str(x)+str(y), map(ord,"hello world")) '10410110810811132119111114108100' 

It is not at all obvious why one would want to concatenate the (decimal) «ascii values». What is certain is that concatenating them without leading zeroes (or some other padding or a delimiter) is useless — nothing can be reliably recovered from such an output.

>>> tests = ["hi", "Hi", "HI", '\x0A\x29\x00\x05'] >>> ["".join("%d" % ord(c) for c in s) for s in tests] ['104105', '72105', '7273', '104105'] 

Note that the first 3 outputs are of different length. Note that the fourth result is the same as the first.

>>> ["".join("%03d" % ord(c) for c in s) for s in tests] ['104105', '072105', '072073', '010041000005'] >>> [" ".join("%d" % ord(c) for c in s) for s in tests] ['104 105', '72 105', '72 73', '10 41 0 5'] >>> ["".join("%02x" % ord(c) for c in s) for s in tests] ['6869', '4869', '4849', '0a290005'] >>> 

Источник

Convert String to ASCII Value in Python

In this post, we will develop a Python program to convert the string to ASCII values. Based on this program we will also develop a program to find the sum of ASCII values of string in Python.

ASCII stands for American Standard Code for Information Interchange. It was developed by the ANSI (American National Standards Institute) and it is used to interchange the information from a high-level language to low-level language. Machine or Computer understand only binary languages. So, the character data type represents integers. For example, the ASCII value of the letter ‘A’ is 65.

Читайте также:  Java throw exception in function

String to ASCII in Python

We will discuss how to convert each character in a string to an ASCII value. We are using the ord() function to convert a character to an integer (ASCII value). Which is a built-in function in Python that accepts a char (a string of length 1) as an argument and returns the Unicode code point for that character. We can use this function to find the ASCII value of any character.

# Python program to find ASCII value of each character in string # take input string = input("Enter any string: ") # printing ascii value of each character for i in range(len(string)): print("The ASCII value of character %c = %d" %(string[i], ord(string[i])))

Enter any string: Python
The ASCII value of character P = 80
The ASCII value of character y = 121
The ASCII value of character t = 116
The ASCII value of character h = 104
The ASCII value of character o = 111
The ASCII value of character n = 110

ASCII Value of String in Python

This is yet another way to find the ASCII value of each character in a string. This is just shorthand to the above program in which we compact the code using list comprehension.

# Python program to find ASCII value of each character in string # take input string = input("Enter any string: ") # find ascii value using list comprehension ASCII_value = [ord(ch) for ch in string] # printing ascii value of each character print("The ASCII value of characters:", ASCII_value)

Enter any string: List
The ASCII value of characters: [76, 105, 115, 116]

Sum of ASCII Values of String in Python

In the previous program, we will find the ASCII value of each character in a string but in this program, we will develop a Python program to find the sum of ASCII values of all characters in a string.

# Python program to find ASCII value of string # take input string = input("Enter any string: ") # find ascii value of string ASCII_value = sum(ord(ch) for ch in string) # printing ascii value print("The ASCII value of characters:", ASCII_value)

Enter any string: ASCII_value
The ASCII value of characters: 997

Python Program to Find String to ASCII

We are using the sum() and map() function to find the sum of ASCII values of all characters in a string. map() is a built-in function that applies a function on all the items of an iterator given as input.

# Python program to find ASCII value of string # take input string = input("Enter any string: ") # find ascii value of string ASCII_value = sum(map(ord, string)) # printing ascii value print("The ASCII value of characters:", ASCII_value)

Enter any string: map function
The ASCII value of characters: 1220

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

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