引自:https://www.cnblogs.com/xunbu7/p/8074417.html
https://www.cnblogs.com/jamsent/p/7183905.html
截取
str = ‘0123456789’
print str[0:3] #截取第一位到第三位的字符
print str[:] #截取字符串的全部字符
print str[6:] #截取第七个字符到结尾
print str[:-3] #截取从头开始到倒数第三个字符之前
print str[2] #截取第三个字符
print str[-1] #截取倒数第一个字符
print str[::-1] #创造一个与原字符串顺序相反的字符串
print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
print str[-3:] #截取倒数第三位到结尾
print str[:-5:-3] #逆序截取,具体啥意思没搞明白?
对应的输出结果:
012
0123456789
6789
0123456
2
9
9876543210
78
789
96
拼接
Python字符串拼接
在Python的实际开发中,很多都需要用到字符串拼接,python中字符串拼接有很多,今天总结一下:
- 用
+
符号拼接 - 用
%
符号拼接 - 用
join()
方法拼接 - 用
format()
方法拼接 - 用
string
模块中的Template
对象
如果还有其他方法,欢迎补充。
例子:
fruit1 = 'apples' fruit2 = 'bananas' fruit3 = 'pears'
要求:
输出字符串’There are apples, bananas, pears on the table’
用+
拼接字符串如下:
1 str = 'There are'+fruit1+','+fruit2+','+fruit3+' on the table'
该方法效率比较低,不建议使用
用%
符号拼接方法如下:
1 str = 'There are %s, %s, %s on the table.' % (fruit1,fruit2,fruit3)
除了用元组的方法,还可以使用字典如下:
1 str = 'There are %(fruit1)s,%(fruit2)s,%(fruit3)s on the table' % {'fruit1':fruit1,'fruit2':fruit2,'fruit3':fruit3}
该方法比较通用
join()`方法拼接如下
1 temp = ['There are ',fruit1,',',fruit2,',',fruit3,' on the table'] 2 ''.join(temp)
该方法使用与序列操作
用format()
方法拼接如下:
4. 用format()
方法拼接
用format()
方法拼接如下:
1 str = 'There are {}, {}, {} on the table' 2 str.format(fruit1,fruit2,fruit3)
还可以指定参数对应位置:
1 str = 'There are {2}, {1}, {0} on the table' 2 str.format(fruit1,fruit2,fruit3) #fruit1出现在0的位置
同样,也可以使用字典:
1 str = 'There are {fruit1}, {fruit2}, {fruit3} on the table' 2 str.format(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3)
用string
模块中的Template
对象如下:
1 from string import Template 2 str = Template('There are ${fruit1}, ${fruit2}, ${fruit3} on the table') #此处用的是{},别搞错了哦 3 str.substitute(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3) #如果缺少参数,或报错如果使用safe_substitute()方法不会 4 str.safe_substitute(fruit1=fruit1,fruit2=fruit2) 5 #输出'There are apples, bananas, ${fruit3} on the table'
总结
拼接的方法有多种,不同场合下使用不同的方法,个人比较推荐%
、format()
方法,简单方便。