41.2k views
0 votes
Write this in python

Write a loop that counts the number of space characters that appear in the string referenced by mystring.

User Ink
by
6.6k points

1 Answer

4 votes

Answer:

mystring = "This is a string with spaces"

count = 0

for char in mystring:

if char == ' ':

count += 1

print("Number of spaces in the string: ", count)

Step-by-step explanation:

Here is a step-by-step explanation of the code:

  1. First, we define a string mystring which we want to count the number of spaces in.
  2. Then, we initialize a variable count to store the number of spaces in the string. We start count at 0.
  3. We then use a for loop to iterate over each character in the string mystring. The loop variable char holds the current character.
  4. Within the loop, we use an if statement to check if the current character char is a space.
  5. If the current character is a space, we increment the count variable by 1 using count += 1.
  6. After the loop, we use the print function to print the final value of count, which is the number of spaces in the string.
  7. The output of the code will be "Number of spaces in the string: x", where x is the number of spaces in the string mystring.
User Archana David
by
7.3k points