经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python3 » 查看文章
python3 字符串/列表/元组(str/list/tuple)相互转换方法及join()函数的使用
来源:jb51  时间:2019/4/3 16:06:25  对本文有异议

在抓取网络数据的时候,有时会用正则对结构化的数据进行提取,比如 href="https://www.1234.com"等。python的re模块的findall()函数会返回一个所有匹配到的内容的列表,在将数据存入数据库时,列表数据类型是不被允许的,而是需要将其转换为元组形式。下面看下,str/list/tuple三者之间怎么相互转换。

  1. class forDatas:
  2. def __init__(self):
  3. pass
  4. def str_list_tuple(self):
  5. s = 'abcde12345'
  6. print('s:', s, type(s))
  7. # str to list
  8. l = list(s)
  9. print('l:', l, type(l))
  10. # str to tuple
  11. t = tuple(s)
  12. print('t:', t, type(t))
  13. # str转化为list/tuple,直接进行转换即可
  14. # 由list/tuple转换为str,则需要借助join()函数来实现
  15. # list to str
  16. s1 = ''.join(l)
  17. print('s1:', s1, type(s1))
  18. # tuple to str
  19. s2 = ''.join(t)
  20. print('s2:', s2, type(s2))

str转化为list/tuple,直接进行转换即可。而由list/tuple转换为str,则需要借助join()函数来实现。join()函数是这样描述的:

  1. """
  2. S.join(iterable) -> str
  3. Return a string which is the concatenation of the strings in the
  4. iterable. The separator between elements is S.
  5. """

join()函数使用时,传入一个可迭代对象,返回一个可迭代的字符串,该字符串元素之间的分隔符是“S”。

传入一个可迭代对象,可以使list,tuple,也可以是str。

  1. s = 'asdf1234'
  2. sss = '@'.join(s)
  3. print(type(sss), sss)

总结

以上所述是小编给大家介绍的python3 字符串/列表/元组(str/list/tuple)相互转换方法及join()函数的使用,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对w3xue网站的支持!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号