简体   繁体   中英

How to get a tally of each letter in a string?

I am tasked with coming with a program that will decyrpt a Cesar cipher, and I was looking at other questions previously asked on this site and understand it mostly. However, I just have a very basic question on how to get a tally of every letter within a string.

here's what I have come up with so far:

Input=input("input the text you want  to decipher:")

import string
print(string.ascii_uppercase)

def get_char(ch,shift):
    #get a tally of the each letter
    common_letter=#letter with most "tallies"
    return common_letter
    print(common_letter)

#finding the shift
def get_shift(s,ignore):
    for x in Input:
       shift=get_char-x
       if shift=='e':
           return x
           print(x)

def output_plaintext(s,shift):

#convert back to English based off shift 
    pass 

def main():
# main body where i call together my other functions
    pass 

input("is this decrypted?")
#if no is inputted re run program with second most common letter

How do I get a count of each letter in a String?

-Nathan

This may help you:-

from collections import Counter
input='Nathannn'
print Counter(input)

Output:-

Counter({'n': 3, 'a': 2, 'h': 1, 't': 1, 'N': 1})

If you want to ignore case use input.lower() and then apply Counter(input)

Here's another approach, if you can't use imported modules, eg collections :

>>> string = 'aardvark'
>>> {letter: string.count(letter) for letter in set(string)}
{'v': 1, 'r': 2, 'd': 1, 'a': 3, 'k': 1}

您可以使用以下代码获取字符串中的最后一个字符:

string[len(string)-1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM