Computer >> Máy Tính >  >> Lập trình >> Python

Hàm zip trong Python để thay đổi thành một bộ ký tự mới.

Với một bộ ký tự 26 chữ cái, ở đây chúng tôi đang sử dụng một bộ ký tự mới. Và một bộ ký tự khác giống như bộ chữ cái (a, b, c ........ z), thì nhiệm vụ của chúng ta là tạo mối quan hệ giữa bộ ký tự mới và bộ chữ cái đó.

Ví dụ

New character set: qwertyuiopasdfghjklzxcvbnm
Input: "wwmm"
Output: bbzy

Thuật toán

Step 1: Given a new character set and input the string to make a relation.
Step 2: and the original character set also given below.
Step 3: Create a dictionary, we use here map technique, we map the English character set and new given character set, zip() does it for us. Both character sets are the map, here we match each character of given character set with each character of new charset sequentially.
Step 4: iterate through the original string and get characters of an original character set.
Step 5: join characters without space to get new string.

Mã mẫu

# Function to change string to a new character 
defnewString(cs,n): 
   ori = 'abcdefghijklmnopqrstuvwxyz'
   newchar = dict(zip(cs,ori)) 
   newstr = [newchar[chr] for chr in n]  
   print (''.join(newstr)) 
# Driver program 
if __name__ == "__main__": 
   newcharSet = 'qwertyuiopasdfghjklzxcvbnm'
   input = 'wwmn'
   newString(newcharSet,input) 

Đầu ra

bbzy