Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python使用for循环打印列表中字符串的前三个字符_Python_Loops_For Loop_Iteration - Fatal编程技术网

Python使用for循环打印列表中字符串的前三个字符

Python使用for循环打印列表中字符串的前三个字符,python,loops,for-loop,iteration,Python,Loops,For Loop,Iteration,我目前正在尝试做一个语句,它将使用for循环打印出列表中每个字符串的前三个字符 for char in lst: if len(char) == 3: print(char) 可以使用Python字符串切片 my_list = ['answer', 'test', 'duh'] for string in my_list: print(string[:3]) 你可以试试这样的 my_strings = ['aaaaaa', 'bbbb', 'ccc'] for el in my

我目前正在尝试做一个语句,它将使用for循环打印出列表中每个字符串的前三个字符

for char in lst:
if len(char) == 3:
    print(char)

可以使用Python字符串切片

my_list = ['answer', 'test', 'duh']
for string in my_list:
  print(string[:3])

你可以试试这样的

my_strings = ['aaaaaa', 'bbbb', 'ccc']

for el in my_strings:
    print el[:3]

它将
打印出
列表中所有字符串的前三个字符
,或者,就像代码所做的那样,它将从索引
0
一直到索引
3
,但不包括索引
3
,然后
打印字符串。

OK!你有问题吗?