Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

รวมตัวอักษรในลิสต์เป็นสตริง (Strings with all given List characters)

แนวคิด

ฟังก์ชันรับลิสต์ตัวอักษร คืนสตริงที่รวมตามลำดับ ใช้ loop บวกสตริง (หรือ join)

ตัวอย่างโค้ด

def convert_to_my_string(my_string_list):
    result = ""
    for ch in my_string_list:
        result += ch
    return result

my_list = ['L', 'e', 'a', 'r', 'n', 'P', 'y', 't', 'h', 'o', 'n', 'c', 'o', 'o', 'l', 'f', 'u', 'n']
print("ลิสต์:", my_list)
print("ผลลัพธ์:", convert_to_my_string(my_list))

ผลลัพธ์

ลิสต์: ['L', 'e', 'a', 'r', 'n', 'P', 'y', 't', 'h', 'o', 'n', 'c', 'o', 'o', 'l', 'f', 'u', 'n']
ผลลัพธ์: LearnPythoncoolfun

วิธีแนะนำ

# ใช้ join - เร็วกว่าและ Pythonic
result = ''.join(my_list)

กรณีลิสต์มีสตริงหลายตัวอักษร

my_list = ['Hello', ' ', 'World', '!']
print(''.join(my_list))  # Hello World!