pythonfor-loopwhile-loop

Counting how many of a certain character there are in a string with one while and one for loop in python


I was given a question with a random string such as

example = ‘asdkfkebansmvajandnrnndklqjjsustjwnwn’

and was asked to find the number of a’s in this string with a while and with a for loop

So simply using the count() function like this is not allowed:

print('# of a:’, example.count(‘a’))

We were given one example: (and were told to find a different way)

counter = 0
for letter in example:
   if letter == ‘a’:
        counter = counter + 1
print(counter)

I’m very new to python and I really can’t find a way. I thought of converting this string into a list that contains every character as a different object like this:

example_list = list(example)

but then I still couldn't find a way.

We were given two starting points, so the end code has to be in a somewhat similar format and we're not really allowed to use more advanced functions (simple string or list functions and if-statements are allowed as far as I know).

For while-loop:

counter = 0
while counter < 4:
    print(example_list[counter])
    counter += 1

And for for-loop:

for counter in range(0, len(example_list)):
    print(counter, example[counter])

I either end up printing every single character with its position, or I end up printing the number without actually using the loop.


Solution

  • I think the advises tell you that you have to iterate through array using a counter. Here is the example for while loop:

    example = 'asdkfkebansmvajandnrnndklqjjsustjwnwn'
    counter = 0
    a_count = 0
    while counter < len(example):
        if example[counter] == 'a':
            a_count += 1
        counter += 1
    print(a_count)
    

    And for for-loop it might look like this:

    for counter in range(len(example)):
        if example[counter] == 'a':
            a_count += 1