【Python 技巧】使用 join() 方法将序列中的元素拼接成字符串

Python 中 join() 方法可以将序列中的元素以指定的字符连接生成一个新的字符串。该序列可以是字符串、元组、列表或者字典

join() 方法的语法:'str'.join(sequence),其中 str:分隔符,可以为空;sequence:要连接的元素序列

对字符串进行操作:

>>> sequence = 'I Love Python'
>>> print('.'.join(sequence))
I. .L.o.v.e. .P.y.t.h.o.n

对元组进行操作:

>>> sequence = ('I', 'Love', 'Python')
>>> print(''.join(sequence))
ILovePython

>>> sequence = ('I', 'Love', 'Python')
>>> print('-'.join(sequence))
I-Love-Python

对列表进行操作:

>>> sequence = ['I', 'Love', 'Python']
>>> print(''.join(sequence))
ILovePython

>>> sequence = ['I', 'Love', 'Python']
>>> print('+'.join(sequence))
I+Love+Python

对字典进行操作(只会对字典的键进行连接):

>>> sequence = {'a':1, 'b':2, 'c':3, 'd':4}
>>> print(''.join(sequence))
abcd

>>> sequence = {'a':1, 'b':2, 'c':3, 'd':4}
>>> print('_'.join(sequence))
a_b_c_d

在 Python 中还有一个 os.path.join() 方法,此方法属于 os.path 模块,该方法的作用是拼接一个或多个路径,需要注意以下几点:

  • 如果各组件名首字母不包含 \,则函数会自动加上
  • 如果最后一个组件为空,则生成的路径以一个 \ 分隔符结尾
  • 如果有一个组件是一个绝对路径,则在它之前的所有组件均会被舍弃

情况一:各组件名首字母不包含 \

>>> import os
>>>
>>> Path1 = 'home'
>>> Path2 = 'language'
>>> Path3 = 'python'
>>> 
>>> Path = os.path.join(Path1, Path2, Path3)
>>> print('Path =', Path)
Path = home\language\python

情况二:最后一个组件为空

>>> import os
>>> 
>>> Path1 = 'home'
>>> Path2 = 'language'
>>> Path3 = ''
>>> 
>>> Path = os.path.join(Path1, Path2, Path3)
>>> print('Path =', Path)
Path = home\language\

情况三:其中一个组件是一个绝对路径

>>> import os
>>> 
>>> Path1 = 'home'
>>> Path2 = '\language'
>>> Path3 = 'python'

>>> Path = os.path.join(Path1, Path2, Path3)
>>> print('Path =', Path)
>>> Path = \language\python
发布了149 篇原创文章 · 获赞 518 · 访问量 46万+

猜你喜欢

转载自blog.csdn.net/qq_36759224/article/details/104382408
今日推荐