Python——帶所有給定列表字元的字串


當需要查詢包含列表中給定所有字元的字串時,可以定義一種方法,它將字串作為引數,遍歷字串,並向其中新增索引值。

示例

以下為示例演示:

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

說明

  • 定義了一個名為“convert_to_my_string”的方法,它將字串作為引數。

  • 定義一個空字串。

  • 遍歷原始引數,並將元素新增到空字串中。

  • 將其作為輸出返回。

  • 在函式外部,定義一個字元列表,並將其顯示在控制檯上。

  • 透過傳給它每個字元來呼叫該方法。

  • 結果以輸出的形式顯示在控制檯上。

更新於:2021 年 9 月 13 日

279 次瀏覽

開啟您的職業生涯

完成課程認證

開始
廣告