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

在Python2中map函数会返回一个list列表,但在Python3中,返回<map object at 0x********> 

map() 会根据提供的函数对指定序列做映射。

第一个参数 function 以参数序列中的每一个元素调用 function 函数,得到包含每次 function 函数返回值的新列表,返回一个将 function 应用于 iterable 中每一项并输出其结果的迭代器。 如果传入了额外的 iterable 参数,function 必须接受相同个数的实参并被应用于从所有可迭代对象中并行获取的项。 当有多个可迭代对象时,最短的可迭代对象耗尽则整个迭代就将结束。。

语法

map() 函数语法:

map(function, iterable, ...)

参数

  • function -- 函数
  • iterable -- 一个或多个序列

print(map(str, [1, 2, 3, 4]))

list(map(str, [1, 2, 3, 4])) #若无外面的list,则返回<map object at 0x********> 

结果为:

['1', '2', '3', '4']

Python中有.join()和os.path.join()两个函数,具体作用如下:

. join(): 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串

os.path.join(): 将多个路径组合后返回


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)

print("*".join([1,2,3,4]))

print("*".join(map(str,[1,2,3,4])))

对序列进行操作(分别使用' ' 、' - '与':'作为分隔符)

a=['1aa','2bb','3cc','4dd','5ee']
print(' '.join(a))   #1aa 2bb 3cc 4dd 5ee
print(';'.join(a))   #1aa;2bb;3cc;4dd;5ee
print('.'.join(a))   #1aa.2bb.3cc.4dd.5ee
print('-'.join(a))   #1aa-2bb-3cc-4dd-5ee

对字符串进行操作(分别使用' ' 、' - '与':'作为分隔符)

b='hello world'

print(' '.join(b)) # h e l l o   w o r l d

print('-'.join(b))  # h-e-l-l-o- -w-o-r-l-d

print(':'.join(b))  # h:e:l:l:o: :w:o:r:l:d

对元组进行操作(分别使用' ' 、' - '与':'作为分隔符)

c=('aa','bb','cc','dd','ee')

print(' '.join(c)) # aa bb cc dd ee

print('-'.join(c))  # aa-bb-cc-dd-ee

print(':'.join(c))  # aa:bb:cc:dd:ee

对字典进行无序操作(分别使用' ' 、' - '与':'作为分隔符)

d={'name1':'a','name2':'b','name3':'c','name4':'d'}

print(' '.join(d)) # name1 name2 name3 name4

print('-'.join(d))  # name1-name2-name3-name4

print(':'.join(d))  # name1:name2:name3:name4

对于字符串截取后使用join拼接

str='QQ群号-1106112426'

print(str.split('-')[1:]) #截取从第一个往后 ['放假安排']



print('-'.join('QQ群号-学习交流群-互相学习-1106112426'.split('-')[1:])) #截取从第一个往后的所有,并且使用 - 连接; 杭州峰会-放假时间-放假安排



str1='QQ群号-学习交流群-互相学习'

print('-'.join(str1.split('-')[:-1]) ) #截取后,去除最后一个



print('QQ群号-学习交流群-互相学习'.split('-')[-1]) # 取出最后一个-后内容

对目录进行操作

import os

print(os.path.join('/hello/','good/date/','datbody'))  #/hello/good/date/datbody

猜你喜欢

转载自blog.csdn.net/q1246192888/article/details/112625056