小编给大家分享一下python3中字符串、列表、元组相互转换方法及使用join()函数的示例分析,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
在抓取网络数据的时候,有时会用正则对结构化的数据进行提取,比如 href="https://www.1234.com"等。python的re模块的findall()函数会返回一个所有匹配到的内容的列表,在将数据存入数据库时,列表数据类型是不被允许的,而是需要将其转换为元组形式。下面看下,str/list/tuple三者之间怎么相互转换。
class forDatas:
def __init__(self):
pass
def str_list_tuple(self):
s = 'abcde12345'
print('s:', s, type(s))
# str to list
l = list(s)
print('l:', l, type(l))
# str to tuple
t = tuple(s)
print('t:', t, type(t))
# str转化为list/tuple,直接进行转换即可
# 由list/tuple转换为str,则需要借助join()函数来实现
# list to str
s1 = ''.join(l)
print('s1:', s1, type(s1))
# tuple to str
s2 = ''.join(t)
print('s2:', s2, type(s2))
str转化为list/tuple,直接进行转换即可。而由list/tuple转换为str,则需要借助join()函数来实现。join()函数是这样描述的:
"""
S.join(iterable) -> str
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
"""
join()函数使用时,传入一个可迭代对象,返回一个可迭代的字符串,该字符串元素之间的分隔符是“S”。
传入一个可迭代对象,可以使list,tuple,也可以是str。
s = 'asdf1234'
sss = '@'.join(s)
print(type(sss), sss)
看完了这篇文章,相信你对“python3中字符串、列表、元组相互转换方法及使用join()函数的示例分析”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。