Coders Packet

Increment characters and numbers in a string using Python.

By Anay Ravindra Karanje

In this article, we will learn how to increment or decrement the letters and numbers inside a string in Python.

This program makes use of two built-in functions in python i.e. ord() and chr().

The ord() function:

The ord() or ordinal function in python gives the ASCII (American Standard Code for Information Interchange) value of characters that are passed inside the ord() function. So this function basically converts characters into numbers.

Example:

print(ord("A"))
print(ord("4"))
print(ord("7"))

 

The chr() function:

The chr() function takes the ASCII value as an input and returns the corresponding character to that ASCII value as an output.

Example:

print(chr(65))
print(chr(52)) 
print(chr(55)) 

Working:

First, we take the string as an input.

Then we take the integer as an input by which we want to increment each letter.

Then we create two empty lists i.e. 'ascii_values' and 'char_values'.

Next, we iterate over the input string and take the ASCII value of each letter using the ord() function and store it in the 'ascii' variable.

Then we increment the 'ascii' variable by the value 'k' and append it in the 'ascii_values' list.

Then we iterate over the 'ascii_values' list and convert the ASCII value(integer) to their corresponding character and store it in the 'enc' variable.

Next, we append the 'enc' variable to the 'char_values' list.

Lastly, we print the 'char_values' list using end=' '.

string = input("Enter the string you want to increment \n")
k = int(input("Enter the value by which you want to increment the string \n"))

ascii_values = []
char_values = []

for i in string:
ascii = ord(i)
ascii += k
ascii_values.append(ascii)

for i in ascii_values:
enc = chr(i)
char_values.append(enc)

for i in char_values:
print(i, end='')

Output:

Enter the string you want to increment 
abcd1234
Enter the value by which you want to increment the string 
2

cdef3456

 

Download project

Reviews Report

Submitted by Anay Ravindra Karanje (Anay250)

Download packets of source code on Coders Packet