Python——带所有给定列表字符的字符串


当需要查找包含列表中给定所有字符的字符串时,可以定义一种方法,它将字符串作为参数,遍历字符串,并向其中添加索引值。

示例

以下为示例演示:

Open Compiler
print("Method definition begins...") def convert_to_my_string(my_string): my_result = "" for index in my_string: my_result += index return my_result print("Method definition ends...") my_string = ['L','e','a','r','n','P','y','t','h','o','n', 'c', 'o', 'o', 'l', 'f', 'u', 'n'] print("The list is : " ) print(my_string) print("The resultant string is : ") print(convert_to_my_string(my_string))

输出

Method definition begins...
Method definition ends...
The list is :
['L', 'e', 'a', 'r', 'n', 'P', 'y', 't', 'h', 'o', 'n', 'c', 'o', 'o', 'l', 'f', 'u', 'n']
The resultant string is :
LearnPythoncoolfun

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

说明

  • 定义了一个名为“convert_to_my_string”的方法,它将字符串作为参数。

  • 定义一个空字符串。

  • 遍历原始参数,并将元素添加到空字符串中。

  • 将其作为输出返回。

  • 在函数外部,定义一个字符列表,并将其显示在控制台上。

  • 通过传给它每个字符来调用该方法。

  • 结果以输出的形式显示在控制台上。

更新于:2021 年 9 月 13 日

279 次浏览

开启您的职业生涯

完成课程认证

开始
广告