Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python count of letters in string

#using dict comprehensions
sentence = "This is a long sentence that I have just written up for an example!"
dicto = {char:  sentence.count(char) for char in set(sentence)}
print(dicto)#This returns a dictionary with the letter and amount of times it shows up in your sentence
#output: {'f': 1, 'u': 2, 't': 6, 's': 4, 'j': 1, 'o': 2, 'I': 1, 'r': 2, 'p': 2, 'w': 1, '!': 1, 'l': 2, 'n': 5, 'g': 1, 'T': 1, 'a': 5, 'h': 3, 'i': 3, 'v': 1, 'm': 1, 'e': 7, 'c': 1, ' ': 13, 'x': 1}
#sorted low to high:
print({k: v for k, v in sorted(dicto.items(), key=lambda item: item[1])})
#{'g': 1, 'x': 1, 'j': 1, 'f': 1, '!': 1, 'T': 1, 'w': 1, 'v': 1, 'I': 1, 'm': 1, 'c': 1, 'o': 2, 'u': 2, 'r': 2, 'l': 2, 'p': 2, 'i': 3, 'h': 3, 's': 4, 'n': 5, 'a': 5, 't': 6, 'e': 7, ' ': 13}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #python #count #letters #string
ADD COMMENT
Topic
Name
7+7 =