Python解析器st2tuple()函数的用法和示例
发布时间:2023-12-15 22:06:50
Python解析器中的st2tuple()函数可以将字符串转换为元组。它的语法如下:
st2tuple(string)
其中,string是要转换为元组的字符串。
示例:
1. 将字符串转换为元组:
string = "Hello, World!" tuple = st2tuple(string) print(tuple)
输出:
('H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!')
2. 将数字字符串转换为元组:
string = "12345" tuple = st2tuple(string) print(tuple)
输出:
('1', '2', '3', '4', '5')
3. 将空字符串转换为元组:
string = "" tuple = st2tuple(string) print(tuple)
输出:
()
可以看到,st2tuple()函数将字符串中的每个字符分别转换为元组的元素。如果字符串为空,则返回一个空元组。
需要注意的是,st2tuple()函数返回的是一个元组,如果需要将其转换为列表,可以使用list()函数。例如:
string = "Hello, World!" tuple = st2tuple(string) list = list(tuple) print(list)
输出:
['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
