简体   繁体   中英

For loop for defining index and len() in python

Task 1: Python's len(..) function takes in a string or a list , and returns its length. Using the len(..) function, for each letter in the string “Mississippi”, print “Letter i of Mississippi is: ” and the letter, where i is that letter's index in the string. When concatenating a string and an integer, don't forget to cast the integer as a string, as shown in Table 3.

This is the task and and i tried this code, but it gives me back only 1,2,3,4,5...

I doubt this is what they want to see.

>>> city
'Mississippi'
>>> for i in range(len(city)):
    print("Letter i of Mississippi is : " + city[i], str(i))

You were almost there

for i in range(len(city)):
    print("Letter {} of Mississippi is : {}".format(i, city[I]))

    print( "Letter " + str(i) + "...")

You should concatenate i (the variable) into the middle of the string, in place of i (the letter).

for i in range(len(city)):
    print("Letter " + str(i) + " of Mississippi is: " + city[i])

You can print as follows:

for i in range(len(city)):
    print(f"Letter {i} of Mississippi is : {city[i]}")

Solution 1:

for i in range(len(city)):
    print(f"Letter {city[i]} of Mississippi is at index {str(i)}")
Letter M of Mississippi is at index 0
Letter i of Mississippi is at index 1
Letter s of Mississippi is at index 2
Letter s of Mississippi is at index 3
Letter i of Mississippi is at index 4
Letter s of Mississippi is at index 5
Letter s of Mississippi is at index 6
Letter i of Mississippi is at index 7
Letter p of Mississippi is at index 8
Letter p of Mississippi is at index 9
Letter i of Mississippi is at index 10

Solution 2 using list comprehension:

[f"Letter {city[i]} of Mississippi is at index {str(i)}" for i in range(len(city))]
['Letter M of Mississippi is at index 0',
 'Letter i of Mississippi is at index 1',
 'Letter s of Mississippi is at index 2',
 'Letter s of Mississippi is at index 3',
 'Letter i of Mississippi is at index 4',
 'Letter s of Mississippi is at index 5',
 'Letter s of Mississippi is at index 6',
 'Letter i of Mississippi is at index 7',
 'Letter p of Mississippi is at index 8',
 'Letter p of Mississippi is at index 9',
 'Letter i of Mississippi is at index 10']

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