
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Caesar Cipher in Python
Suppose we have a lowercase alphabet string s, and an offset number say k. We have to replace every letter in s with a letter k positions further along the alphabet. We have to keep in mind that when the letter overflows past a or z, it gets wrapped around the other side.
So, if the input is like "hello", k = 3, then the output will be "khoor"
To solve this, we will follow these steps −
Define a function shift(). This will take c
i := ASCII of (c) - ASCII of ('a')
i := i + k
i := i mod 26
return character from ASCII (ASCII of ('a') + i)
From the main method, do the following −
ret := for each character c in s, make a list of elements by calling shift(c)
return ret
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, s, k): def shift(c): i = ord(c) - ord('a') i += k i %= 26 return chr(ord('a') + i) return "".join(map(shift, s)) ob = Solution() print(ob.solve("hello", 3))
Input
"hello", 3
Output
khoor
- Related Articles
- Caesar Cipher in Cryptography
- Encrypting a string using Caesar Cipher in JavaScript
- Atbash cipher in Python
- C++ Program to Implement Caesar Cypher
- Difference between Block Cipher and Stream Cipher
- Difference between Monoalphabetic Cipher and Polyalphabetic Cipher
- Program to encrypt a string using Vertical Cipher in Python
- Program to encrypt a string using Vigenere cipher in Python
- XOR Cipher in C++
- Bifid Cipher in Cryptography
- Difference between Substitution Cipher Technique and Transposition Cipher Technique
- What is the comparison between Stream Cipher and Block Cipher in information security?
- Polybius Square Cipher in C++
- The Symmetric Cipher Model
- What is Block Cipher in information security?

Advertisements