0

I have a list of item as follows:

language = ["python", "C", "C++", "Java"]

I want to print a list item as follows:

w[0] = "Pyhon"
w[1] = "C"
W[2] = "C++"

I have tried as follow:

for id, elem in enumerate(language):
    if elem is not None:
        print("w['id']=",elem)

However it is not working as per my requirement.

1
  • "w['id']=" is a hard coded string. You need print ('w[{0}]="{1}"'.format(id,elem)). Here is the documentation link Commented Oct 22, 2015 at 1:56

3 Answers 3

6

When you print - print("w['id']=",elem) - Python would not automatically substitute the id inside the string, you would need to format the string correctly so that id is printed there.

You can use str.format() for that. Example -

for id, elem in enumerate(language):
        if elem is not None:
            print("w[{0}] = {1}".format(id,elem))

If you want the elements in the output within quotes, you can use the following print function call -

print('w[{0}] = "{1}"'.format(id,elem))

If you want the first letter capitalized, then -

print('w[{0}] = "{1}"'.format(id,elem.capitalize()))
Sign up to request clarification or add additional context in comments.

2 Comments

You beat me to it with a slightly different method!
@akira, Please accept sufficient answers with the checkmark button. It's worth +2 rep to you.
3

The string in w['id']= is being treated as a literal string, that would work in PHP but not python. Use string concatenation like this:

language =["python","C","C++","Java"]

for id, elem in enumerate(language):
    if elem is not None:
        print('w[%s] = "%s"' % (id, elem))

Comments

0
for id, elem in enumerate(language):
    if elem:
        print('w[{}]="{}"'.format(id,elem))

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.