1. 程式人生 > 其它 >python3 字串/列表/元組(str/list/tuple)相互轉換方法及join()函式的使用 map() 函式

python3 字串/列表/元組(str/list/tuple)相互轉換方法及join()函式的使用 map() 函式

技術標籤:python字串列表python

在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