Shift the alphabet string by N characters in Python

AtCoder's ABC146 B Problem gave me the opportunity to become familiar with Unicode.

Suppose that "shifting an alphabetic character string by N characters" means "converting to the one after N characters in alphabetical order", and after'Z', it returns to'A'. The same definition applies to problem B above.

Built-in functions ord () `` `and chr () `` `

Python3 implements the built-in functions ord () `` `and chr () `` `, which convert characters and their Unicode code points back to each other. Reference: [Python3.8 official document #ord] (https://docs.python.org/ja/3/library/functions.html#ord)

sample


>>> ord('A')
65
>>> ord('D')
68

>>> chr(65)
'A'
>>> chr(70)
'F'

As you can see, it is called "Unicode code point", but it breaks through with the recognition of "a world where various character symbols are represented by a one-to-one correspondence with numbers". Japanese is a world with a lot of expressions, so [books that look good](https://www.amazon.co.jp/%E6%94%B9%E8%A8%82%E6 % 96% B0% E7% 89% 88-% E3% 83% 97% E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9E% E3% 81% AE% E3% 81% 9F% E3% 82% 81% E3% 81% AE% E6% 96% 87% E5% AD% 97% E3% 82% B3% E3% 83% BC% E3% 83% 89% E6% 8A% 80% E8% A1% 93% E5% 85% A5% E9% 96% 80-WEB-PRESS-plus% E3% 82% B7% E3% 83% AA% E3% 83% BC% E3% 82% BA / dp / 4297102919 / ref = sr_1_1? __mk_ja_JP =% E3% 82% AB% E3% 82% BF% E3% 82% AB% E3% 83% 8A & keywords =% E6% 96% 87% E5% AD% 97% E3% 82% B3% E3% 83% BC% E3% 83% 89 & qid = 1585548181 & sr = 8-1).

Apparently, for the uppercase alphabet,'A' is code 65, and from there it is a serial number in decimal. By the way, between uppercase and lowercase

sample



>>> ord('Z')
90
>>> chr(91)
'['
>>> chr(92)
'\\'
>>> chr(93)
']'
>>> chr(94)
'^'
>>> chr(95)
'_'
>>> chr(96)
'`'
>>> chr(97)
'a'

And some symbols were sandwiched. Hmm.

Implementation notes

As you may have noticed in the arguments, both ord () `` `and chr () `assume single character conversion. When converting the character string S, convert it to the empty string '' one character at a time with the `for``` statement, then combine and repeat.

And in order to consider when returning from'Z'to'A', add the remainder `` `, which is the integer obtained by adding N to the original character code point by 26, to the code point of'A'. Calculate the character code point after conversion with.

rot_n.py



def rot_n(s, n):
    answer = ''
    for letter in s:
        answer += chr(ord('A') + (ord(letter)-ord('A')+n) % 26)

    return answer

I will check it.

test_rot



>>> rot_n('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 13)
'NOPQRSTUVWXYZABCDEFGHIJKLM'

Click here for submission of AtCoder B problem ↓

b.py



def rot_n():
    n = int(input())
    s = input()

    answer = ''
    for letter in s:
        answer += chr(ord('A') + (ord(letter)-ord('A')+n) % 26)

    print(answer)


if __name__ == '__main__':
    rot_n()

By the way, the function that restores the converted character string S (shifts it before N characters) is

derot_n.py



def derot_n(s, n):
    answer = ''
    for letter in s:
        answer += chr(ord('Z') - (ord('Z')-ord(letter)+n) % 26)
        
    return answer

It will be.

test_derot



>>> derot_n('NOPQRSTUVWXYZABCDEFGHIJKLM', 13)
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

Miscellaneous notes: ROT N?

I learned from the AtCoder problem I wrote at the beginning. You've generalized ROT13, which is a simple cipher that shifts 13 characters back.

Recommended Posts

Shift the alphabet string by N characters in Python
Divides the character string by the specified number of characters. In Ruby and Python.
Read the file line by line in Python
Read the file line by line in Python
Fill the string with zeros in python and count some characters from the string
Check if the characters are similar in Python
How to erase the characters output by Python
json.dumping None in python returns the string null
Split camel case string word by word in Python
String manipulation in python
Get the last element of the array by splitting the string in Python and PHP
Display n digits after the decimal point in python
Check if the string is a number in python
Store the stock price scraped by Python in the DB
Extract the element by deleting the tag contained in the string
Download the file in Python
String object methods in Python
Find the difference in Python
[Python 2/3] Parse the format string
String date manipulation in Python
Sort by date in python
Find out the apparent width of a string in python
[Python] Open the csv file in the folder specified by pandas
Visualize the correlation matrix by principal component analysis in Python
How to quickly count the frequency of appearance of characters from a character string in Python?
Count the number of Thai and Arabic characters well in Python
Getting the arXiv API in Python
Python in the browser: Brython's recommendation
Shift the data for 3 months Shift the data for n months
Save the binary file in Python
Hit the Sesami API in Python
[Understanding in the figure] Management of Python virtual environment by Pipenv
Check if the password hash generated by PHP matches in Python
Get the desktop path in Python
python: Use the variables defined in the string format as they are
Get the script path in Python
Read the standard output of a subprocess line by line in Python
In the python command python points to python3.8
Implement the Singleton pattern in Python
Display characters like AA in python
Sort the file names obtained by Python glob in numerical order
Hit the web API in Python
cout << "Hello, World! \ N" in python
6 ways to string objects in Python
I wrote the queue in Python
Calculate the previous month in Python
Examine the object's class in python
Get the desktop path in Python
Get the host name in Python
[Python] Do not put Japanese in the path used by OpenCV
Access the Twitter API in Python
Create a random string in Python
Get the formula in an excel file as a string in Python
The first step in Python Matplotlib
Play by hitting the Riot Games API in Python First half
I wrote the stack in Python
Get the query string (query string) in Django
Master the weakref module in Python
[Python] Change the alphabet to numbers
A memo organized by renaming the file names in the folder with python
The eval () function that calculates a string as an expression in python