在Python中,字符串之间的转换可以通过多种方法实现,以下是一些常见的方法:
字符串转列表
使用`list()`函数将字符串转换为字符列表。
s = "hello"lst = list(s)print(lst) 输出:['h', 'e', 'l', 'l', 'o']
使用循环和`append()`方法将字符串转换为字符列表。
s = "hello"ls = []for i in s:ls.append(i)print(ls) 输出:['h', 'e', 'l', 'l', 'o']
字符串转字节串
使用`encode()`方法将字符串转换为字节串。
s = "你好"s_encoded = s.encode("utf-8")print(s_encoded) 输出:b'\xe4\xbd\xa0\xe5\xa5\xbd'
使用`decode()`方法将字节串转换为字符串。
s_encoded = b'\xe4\xbd\xa0\xe5\xa5\xbd's_decoded = s_encoded.decode("utf-8")print(s_decoded) 输出:你好
字符串转数字
使用`int()`函数将字符串转换为整数。
s = "123"n = int(s)print(n) 输出:123

使用`float()`函数将字符串转换为浮点数。
s = "123.456"n = float(s)print(n) 输出:123.456
列表转字符串
使用`join()`方法将列表中的元素连接成字符串。
list1 = ["xxx", "yyy", "zzz"]s = " ".join(list1)print(s) 输出:xxx yyy zzz
使用`str.join()`方法将可迭代对象连接成字符串。
list1 = ["xxx", "yyy", "zzz"]s = "_".join(list1)print(s) 输出:xxx_yyy_zzz
字符串反转
使用切片反转字符串。
s = "hello"s = s[::-1]print(s) 输出:olleh
使用`reversed()`函数反转字符串。
s = "hello"s = "".join(reversed(s))print(s) 输出:olleh
以上方法可以帮助你在Python中实现字符串之间的转换。
