简体   繁体   中英

How to properly iterate through a for loop with python

I am relatively inexperienced and come from c#. I am attempting to iterate through a string and individually print out each letter using a for loop.

In c# this would (if I remember correctly) be written like so:

 string x = test;
 foreach(i in x)
 {
  print(x[i]);
 }

But in python, when I type

  x = "test"
  for i in x:
    print(x[i])

The python shell tells me that i must be an integer.

I am actually pretty sure that my syntax is incorrect in my c# example, but to get to the question:

How would i properly iterate through a string using a for, or foreach loop in Python?

I have been searching the web and am somehow coming up empty handed. Sorry if this is a foolish inquiry.

Your variable x is a string type, therefore, when you type x[i] you are going to get the letter at the position i .

However, in your loop, you have something different:

x = "test"
for i in x:
    print(x[i])

This for loop ( for i in x ) means: for each letter i in the string x, do the following . So, your i variable is actually a letter, not an integer.

So, to print every letter of the string x , just use print(i) :

x = "test"
for i in x:
    print(i)

But, if you really want your i to be an integer, instead of for i in x , use for i in range(0, len(x)) . And in this case, you would have to access the letter by using what you originally wrote ( x[i] ).

x = "test"
for i in range(0, len(x)):
    print(x[i])

If you really want a loop index for some reason, you can use enumerate :

x = 'test'
for i, c in enumerate(x):
    print(i, x[i], c)

This took me a bit to understand as well, but I think I understand the misunderstanding. The i in for i in x already refers to the character, not the index. For example, writing

stringx='hello world for i in stringx: print stringx[i] is the same as writing

print stringx['h']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM