Reputation: 531
Let's say I have
myString = "ORANGE"
How can I write a for-each loop that lists each character so it looks like this
1O
2R
3A
4N
5G
6E
I am confused as I don't know how to do it without using range.
Upvotes: 3
Views: 2088
Reputation: 384
try this
myString = "ORANGE"
for id, val in enumerate(myString, 1):
print("".join(str(id) + val))
Upvotes: 0
Reputation: 2159
Simple way to do this:
myString = "ORANGE"
for i in range(0,len(myString)):
print (str(i+1)+""+myString[i])
Without using range
:
myString = "ORANGE"
j=1
for i in myString:
print (str(j)+""+i)
j+=1
Upvotes: 1
Reputation: 11605
This is quite basic. 5 answers and none of them actually say this I am surprised. Never mind this should do what you asked for:
myString = "ORANGE"
a = 1
for i in myString:
print(str(a) + i)
a = a + 1
Upvotes: 2
Reputation: 4449
for index, character in enumerate('ORANGE'):
print('{}{}'.format(index + 1, character))
Python docs on enumerate
Upvotes: 1
Reputation: 3547
myString = "ORANGE"
l = [str(i)+j for i,j in enumerate(myString,1)]
' '.join(l)
Output:
'1O 2R 3A 4N 5G 6E'
Upvotes: 1