Please tell me how to eterate the string

Asked 2 years ago, Updated 2 years ago, 85 views

In C++, when approaching a string alphabetically

for (int i = 0; i < str.length(); ++i)
    std::cout << str[i] << std::endl;

I did it like this. What do I do with Python?

string python iteration

2022-09-22 14:10

1 Answers

As with other iterations, such as lists and tuples, strings can be translated in the following ways:

for c in "string":
    #What kind of chords?

An object that can be interpreted in Python has the __iter__ attribute in the object. So, to determine which object is of type itable, check if the object has hasattr(someOBJ.__iter__) In fact, Python's repeat statements can translate almost any type (the object has __iter__ attributes). For example, you can eterate a file object to read the contents of the file.

filename = open("file.txt")
for line in open(filename):
    print line


2022-09-22 14:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.