VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > python入门教程 >
  • 8种Python字符串拼接的方法,你知道几种?

一、join函数

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

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

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

列表

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

list1 = ["123", "456", "789"]
print(''.join(list1)) # '123456789'
print('-'.join(list1)) # '123-456-789'

元组

#Python学习交流群:531509025
tuple1 = ('abc', 'dd', 'ff')
print(''.join(tuple1)) # 'abcddff'
print('*'.join(tuple1)) # 'abc*dd*ff'

字符串

str1 = "hello Hider"
print(''.join(str1))
print(':'.join(str1))
# 'h:e:l:l:o: :H:i:d:e:r'

字典

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

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

# 值也必须是字符才可以拼接
dict1 = {"a":1, "b":2, "c":3}
print('*'.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
print(os.path.join('/hello/', 'good/boy/', 'Hider'))
# '/hello/good/boy/Hider'

三、+ 号连接

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

text1 = "Hello"
text2 = "Hider"
print(text1 + text2) # 'HelloHider'

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

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

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

#Python学习交流群:531509025

text1 = "Hello"
text2 = "Hider"
print(text1 , text2) # ('Hello', 'Hider')
print(type((text1, text2))) # <class 'tuple'>

五、%s占位符 or format连接

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

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

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

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

六、空格自动连接

print("Hello" "Hider")# 'HelloHider'

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

七、*号连接

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

text1 = "Hider"
print(text1 * 5) # 'HiderHiderHiderHiderHider'

八、多行字符串连接()

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

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

来源:https://www.cnblogs.com/djdjdj123/p/15449510.html


相关教程