Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: how to generate char by adding int

Tags:

python

I can use 'a'+1 to get 'b' in C language, so what the convient way to do this in Python?
I can write it like:

chr(ord('a')+1)

but I don't know whether it is the best way.

like image 891
remy Avatar asked Mar 16 '12 15:03

remy


People also ask

How do you add an int to a char?

Example 3: int to char by adding '0' Here, the character '0' is converted into ASCII value 48. The value 48 is added to the value of num1 (i.e. 1). The result 49 is the ASCII value of 1. Hence, we get the character '1' as the output.

Can we assign integer value to character?

We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable. To get the actual value in char variable, you can add '0' with int variable.

How do you convert int to ASCII in Python?

chr () is a built-in function in Python that is used to convert the ASCII code into its corresponding character. The parameter passed in the function is a numeric, integer type value. The function returns a character for which the parameter is the ASCII code.

What happens when you add a char to an int?

If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method. Alternatively, we can use String.


2 Answers

Yes, this is the best way. Python doesn't automatically convert between a character and an int the way C and C++ do.

like image 89
Mark Ransom Avatar answered Nov 03 '22 06:11

Mark Ransom


Python doesn't actually have a character type, unlike C, so yea, chr(ord is the way to do it.

If you wanted to do it a bit more cleanly, you could do something like:

def add(c, x):
  return chr(ord(c)+x)
like image 33
Tyler Eaves Avatar answered Nov 03 '22 07:11

Tyler Eaves