Python 程序从字符串列表中提取给定范围内的字符


当需要从字符串列表中提取给定范围的字符时,将使用列表解析和列表切片。

示例

以下是演示:

Open Compiler
my_list = ["python", "is", "fun", "to", "learn"] print("The list is :") print(my_list) start, end = 11, 25 my_result = ''.join([element for element in my_list])[start : end] print("The result is :") print(my_result)

输出

The list is :
['python', 'is', 'fun', 'to', 'learn']
The result is :
tolearn

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义了一个列表并将其显示在控制台上。

  • 定义了 'start' 和 'end' 的值。

  • 使用列表解析遍历列表,提取 'start' 和 'end' 值之间的每个元素,然后使用 'join' 方法消除空格。

  • 该结果被赋值给一个变量。

  • 这是显示在控制台上的输出。

更新于:08-Sep-2021

411 次浏览

开启你的 职业

完成课程以获得认证

开始
广告