Gin Gin - 8 months ago 59
Python Question

How to calculate the fraction of a certain letter within a string?

Hi I would like to know how I can calculate the fraction of certain letters in a string. Like for example if I have the string "ABGTACTGASDJASBFGJAFKA" and want to calculate the fraction of A+D in that string what would I have to do? I want to do this without having to import anything and only using the built in functions of python.

def fraction(string):
A = ""
D = ""
A = string.count("A")
D = string.count("D")
print(int(A/D * 100), "%")

Answer Source

A/D is not a the fraction of a certain letter in the whole sting.

The following line will calculate the percentage of "A" in your string.

100.0 * ( string.count("A") / len(string) )

My suggestion, don't do both characters at once. Start with this

def fraction(string, letter):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download