[英]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.任务 1:Python 的
len(..)
function 接受一个string
或一个list
,并返回其长度。 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.使用
len(..)
function,对于字符串“Mississippi”中的每个字母,打印“Letter i of Mississippi is:”和字母,其中i
是该字母在字符串中的索引。 When concatenating a string and an integer, don't forget to cast the integer as a string, as shown in Table 3.连接字符串和 integer 时,不要忘记将 integer 转换为字符串,如表 3 所示。
This is the task and and i tried this code, but it gives me back only 1,2,3,4,5...
这是任务,我尝试了这段代码,但它只给了我
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).您应该将
i
(变量)连接到字符串的中间,代替i
(字母)。
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:解决方案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:使用列表理解的解决方案 2 :
[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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.