Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string / character to integer in python

I want to convert a single character of a string into an integer, add 2 to it, and then convert it back to a string. Hence, A becomes C, K becomes M, etc.

like image 961
Luke Avatar asked Dec 17 '09 16:12

Luke


People also ask

How will you convert a single character to its integer value in Python?

ord() : This function is used to convert a character to integer.

How can a string be converted to a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.

How do I convert multiple strings to integers in Python?

Method 1: Using eval() Python eval() function parse the expression argument and evaluate it as a python expression and runs Python expression(code), If the expression is an int representation, Python converts the argument to an integer.


1 Answers

This is done through the chr and ord functions. Eg; chr(ord(ch)+2) does what you want. These are fully described here.

like image 129
Nikwin Avatar answered Oct 14 '22 13:10

Nikwin