0

In C#:

List<string> stringList = new List<string>() { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE" };
for (int i = 0; i < stringList.Count; i++)
    Console.WriteLine(i + ": " + stringList[i]);

Output:

0: AAAA
1: BBBB
2: CCCC
3: DDDD
4: EEEE

In Python:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
for i, string in enumerate(stringList):
    print(i + ": " + string)

I want output same as the output above, but there is error:

TypeError: unsupported operand type(s) for +: 'int' and 'str'
1
  • 2
    i is not a string, but an int. Use str(i) Commented Oct 21, 2019 at 4:37

4 Answers 4

4

Try the below code, Hope this helps:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
for i, string in enumerate(stringList):
    print(i ,": ", string)

Ouput will be :

0 :  AAAA
1 :  BBBB
2 :  CCCC
3 :  DDDD
4 :  EEEE
Sign up to request clarification or add additional context in comments.

2 Comments

Or print("{0}: {1}".format(i,string)) to autmaitilly string format index integer
@gtalarico , yes you can also use this method. It is upto your convenience. :)
4

I guess your code is just fine, maybe just a bit modify it:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
for i, string in enumerate(stringList):
    print(f'{i}:  {string}')

Output

0:  AAAA
1:  BBBB
2:  CCCC
3:  DDDD
4:  EEEE

You can also write with list comprehension, if you like:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
[print(f'{i}:  {string}') for i, string in enumerate(stringList)]

Or you can simply build your output first and then print only once:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
output = ''
for i, string in enumerate(stringList):
    output += f'{i}: {string}\n'

print(output)

Comments

0

Just use a while loop:

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
i = 0
while i < len(stringList):
    print(str(i) + ": " + stringList[i])
    i = i + 1

2 Comments

Forgetting i += 1 at the end. Also, whats wrong with a for loop? In this case the list is fixed, so a for loop is probably the better option. A while loop is better in situations where you don't know how many elements your going to process.
@RoadRunner I don't know what the most "Pythonic" way to do this is, but my answer is probably closest to the for loop syntax used in the OP's quoted C# code.
0

I must use str() as per @RoadRunner comment, it will look like the C# which I want

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
for i in range(len(stringList)):
    print(str(i) + ": " + stringList[i])

or

stringList = ["AAAA", "BBBB", "CCCC", "DDDD", "EEEE"]
for i, string in enumerate(stringList):
    print(str(i) + ": " + string)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.