Python学习笔记:字符串连接(join、os.path.join)

一、join函数

join 是 python 中字符串自带的一个方法,返回一个字符串。使用语法为:

sep.join(可迭代对象) --》 str
# sep 分隔符 可以为空

将一个包含多个字符串的可迭代对象(字符串、元组、列表),转为用分隔符sep连接的字符串。

  • 列表

列表必须为非嵌套列表,列表元素为字符串(str)类型

list1 = ["123", "456", "789"]
''.join(list1) # '123456789'
'-'.join(list1) # '123-456-789'
  • 元组
tuple1 = ('abc', 'dd', 'ff')
''.join(tuple1) # 'abcddff'
'*'.join(tuple1) # 'abc*dd*ff'
  • 字符串
str1 = "hello Hider"
''.join(str1)
':'.join(str1)
# 'h:e:l:l:o: :H:i:d:e:r'
  • 字典

默认拼接 key 的列表,取 values 之后拼接值。

dict1 = {"a":1, "b":2, "c":3}
''.join(dict1) # 'abc'
'*'.join(dict1) # 'a*b*c'
# 拼接的是key

# 值也必须是字符才可以拼接
dict1 = {"a":1, "b":2, "c":3}
'*'.join(str(dict1.values()))
# 'd*i*c*t*_*v*a*l*u*e*s*(*[*1*,* *2*,* *3*]*)' 否则

二、os.path.join函数

os.path.join函数将多个路径组合后返回,使用语法为:

os.path.join(path1 [,path2 [,...]])

注:第一个绝对路径之前的参数将被忽略

# 合并目录
import os
os.path.join('/hello/', 'good/boy/', 'Hider')
# '/hello/good/boy/Hider'

三、“+” 号连接

最基本的方式就是使用 “+” 号连接字符串。

text1 = "Hello"
text2 = "Hider"
text1 + text2 # 'HelloHider'

该方法性能差,因为 Python 中字符串是不可变类型,使用“+”号连接相当于生成一个新的字符串,需要重新申请内存,当用“+”号连接非常多的字符串时,将会很耗费内存,可能造成内存溢出。

四、“,”连接成tuple(元组)类型

使用逗号“,”连接字符串,最终会变成 tuple 类型。

text1 = "Hello"
text2 = "Hider"
text1 , text2 # ('Hello', 'Hider')
type((text1, text2)) # tuple

五、“%s”占位符 or format连接

借鉴C语言中的 printf 函数功能,使用%号连接一个字符串和一组变量,字符串中的特殊标记会被自动使用右边变量组中的变量替换。

text1 = "Hello"
text2 = "Hider"
"%s%s" % (text1, text2) # 'HelloHider'

使用 format 格式化字符串也可以进行拼接。

text1 = "Hello"
text2 = "Hider"
"{0}{1}".format(text1, text2) # 'HelloHider'

六、空格自动连接

"Hello" "Hider" # 'HelloHider'

不支持使用参数代替具体的字符串,否则报错。

七、“*” 号连接

这种连接方式相当于 copy 字符串,例如:

text1 = "Hider"
text1 * 5 # 'HiderHiderHiderHiderHider'

八、多行字符串连接()

Python遇到未闭合的小括号,自动将多行拼接为一行,相比3个引号和换行符,这种方式不会把换行符、前导空格当作字符。

text = ('666'
        '555'
        '444'
        '333')
print(text) # 666555444333
print(type(text)) # <class 'str'>

参考链接1:python中join的使用

参考链接2:Python join() 函数 连接字符串

参考链接3:聊聊 Python 字符串连接的七种方式

参考链接4:Python 拼接字符串的几种方式

原文地址:https://www.cnblogs.com/hider/p/14707063.html