Python Forum
counting chars in string w/o len
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
counting chars in string w/o len
#1
Here's my homework assignment:

Write code to count the number of characters in original_str using for loop as a counter and assign the answer to a variable num_chars. Do NOT use the len function to solve the problem.

#Here's my attempt:

original_str = "The quick brown rhino jumped over the extremely lazy fox."
counter=0
for counter in range (original_str):
	counter = counter +  1
num_chars=counter
print(num_chars)
Here's error message:
TypeError: start must be a integer on line 3
Reply
#2
From an interactive prompt, you can type help(range) to see how it expects to be used. The short version, is that it expects a number of how many things you want in the range, so range(10) would generate a sequence of 10 digits, 0 through 9.

That's a whole lot of words to say that range() isn't where you should be with this assignment. Here's a hint, you can iterate over the string directly.
Reply
#3
In addition to what Nilamo said, you want your loop variable to be different from the variable you are using to count the characters.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Counting the number of occurrences of characters in a string nsadams87xx 1 1,915 Jun-16-2020, 07:22 PM
Last Post: bowlofred
  slicing and counting words in a string Rudy 11 6,390 Mar-17-2019, 10:46 PM
Last Post: micseydel
  Counting only letters in a string PraiseYAH 2 4,523 Jul-20-2018, 11:22 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020