python入门容器-列表与字符串转化Day05

列表转换为字符串:

result = "连接符".join(列表)

# 应用
# 需求:根据某个逻辑循环拼接字符串
#       0-9
# result = ""
# for number in range(10):
#     # 缺点:每次循环都会产生新字符串,产生垃圾
#     result += str(number)
# print(result)  # 0123456789

# 解决:将不可变数据改为可变数据
result = []
for number in range(10):
    result.append(str(number))
result = "".join(result)
print(result)  # 0123456789

字符串转换为列表:

列表 = “a-b-c-d”.split(“分隔符”)

"""
    字符串转换为列表:
    列表 = “a-b-c-d”.split(“分隔符”)
"""
result = "a/b/c/d".split("/")
print(result)

# 应用
# 一个字符串记录多个信息
result = "唐僧_孙悟空_八戒".split("_")
print(result)
"""
    练习:将下列英文语句按照单词进行翻转.
    转换前:To have a government that is of people by people for people
    转换后:people for people by people of is that government a have To
"""
message = "To have a government that is of people by people for people"
list_temp = message.split(" ")
message = " ".join(list_temp[::-1])
print(message)

猜你喜欢

转载自blog.csdn.net/LOVE_Me__/article/details/122707925