216k views
1 vote
Write a loop that counts the number of space characters that appear in the string referenced by my_string

write this in python

User Kshenoy
by
8.2k points

2 Answers

4 votes

Answer:

1.

my_string = input("Enter a string: ")

count = 0

for c in my_string:

if c == " ":

count += 1

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

2.

my_string = input("Enter a string: ")

count = my_string.count(" ")

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

Step-by-step explanation:

in number 1, The code reads a string from the user, then uses a loop to iterate over each character in the string and counts the number of spaces in the string. Finally, the code prints the count of spaces.

This is a simple and straightforward way to count the number of spaces in a string, but using Python's built-in count method (in number 2) would make the code shorter and more efficient.

User Jezthomp
by
6.9k points
2 votes

Answer:

Here's a Python code that uses a loop to count the number of space characters in a given string:

my_string = "Hello world! This is a string with spaces."

count_spaces = 0

for char in my_string:

if char == " ":

count_spaces += 1

print("Number of space characters in the string:", count_spaces)

This code initializes a variable count_spaces to 0 and then loops through each character in the my_string string using a for loop. Inside the loop, it checks whether the current character is a space character by comparing it to the space character " ". If it is, it increments the count_spaces variable by 1.

Finally, the code prints the number of space characters found in the string.