python3 字符串/列表/元组(str/list/tuple)相互转换方法及join()函数的使用

yipeiwu_com6年前Python基础

在抓取网络数据的时候,有时会用正则对结构化的数据进行提取,比如 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 字符串/列表/元组(str/list/tuple)相互转换方法及join()函数的使用,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

NLTK 3.2.4 环境搭建教程

NLTK 3.2.4 环境搭建教程

本文记录了NLTK 3.2.4 环境搭建的方法,供大家参考,具体内容如下 系统环境:win7 32位 python:2.7.13,后改为3.6.1 安装NLTK 从网站下载,完成后双击安...

Python实现的端口扫描功能示例

本文实例讲述了Python实现的端口扫描功能。分享给大家供大家参考,具体如下: 一 代码 import sys import socket import multiprocessin...

Python3随机漫步生成数据并绘制

Python3随机漫步生成数据并绘制

本文为大家分享了Python3随机漫步生成数据并绘制的具体代码,供大家参考,具体内容如下 random_walk.py from random import choice #生成随...

python用pandas数据加载、存储与文件格式的实例

数据加载、存储与文件格式 pandas提供了一些用于将表格型数据读取为DataFrame对象的函数。其中read_csv和read_talbe用得最多 pandas中的解析函数: 函数...

Python facenet进行人脸识别测试过程解析

Python facenet进行人脸识别测试过程解析

1.简介:facenet 是基于 TensorFlow 的人脸识别开源库,有兴趣的同学可以扒扒源代码: https://github.com/davidsandberg/facenet...