0

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.

4
  • for i in x grabs each character in x. Indexing with x[i] won't work because you're using a character for the index. Change it to for i in range(len(x)) to get it working correctly. Commented Jun 9, 2016 at 21:00
  • "In c# this would (if I remember correctly) be written like so" - you remember wrong. C# foreach goes over elements rather than indices, just like Python. Commented Jun 9, 2016 at 21:01
  • @user2357112 Yes I realize now after looking at previous practice I had done, thank you Commented Jun 9, 2016 at 22:31
  • @Jim I didn't even think to use len() for something like this, thanks for that! Commented Jun 9, 2016 at 22:31

3 Answers 3

1

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]) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That was very indepth and covered everything I had concerns about.
0

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) 

Comments

0

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'] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.