python3 字符串/列表/元组(str/list/tuple)相互转换方法及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)

 

转载于:https://www.cnblogs.com/zrmw/p/10637114.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值