Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

In C++, I can iterate over an std::string like this:

std::string str = "Hello World!";

for (int i = 0; i < str.length(); ++i)

{

std::cout << str[i] << std::endl;

}

How do I iterate over a string in Python?

1 Answer

0 votes
by (106k points)

There are many ways to iterate over a string in Python:-

The first thing you can use a for loop to iterate over a given string like as follows:-

for c in "Delhi":

    print(c)

image

Another way is to use enumerate()so If you need access to the index as you iterate through the string, by using enumerate() below is the code that explains the use of enumerate():-

for i, c in enumerate('Delhi'):

      print(i, c)

image

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...