Python 数据类型--String(字符串)

2 string(字符串)

2.1 字符串基本操作

2.1.1字符串创建

创建字符串很简单,只要为变量分配一个值即可

string = "hello"
print(string)
hello

2.1.2字符串拼接

字符串是Python中最常用的数据类型。我们可以使用引号('或")创建字符串。
通常字符串不能进行数学操作,即使看起来像数字也不行。字符串不能进行除法、减法和字符串之间的乘法运算。

string1 = "hello"
space = " "
string2 = "world."
print(string1+space+string2)
hello world.

2.1.3字符串索引

string = "just do it."
print(string[0])
print(string[2])
print(string[-1])
j
s
.

2.1.4字符串求长度

len(string)
10

2.1.5字符串分片

string[-3:]
'it.'

2.1.6字符串取最大,最小值

str = "12345abcde$*"
max(str)
'e'
min(str)
'$'

2.1.7字符串转义字符的应用

#换行符 

print("1234
abcd")
1234
abcd
# 制表符 	
print("	abcd	1234")
	abcd	1234

2.2字符串格式化

字符串格式化使用操作符百分号(%)实现。

提示: %也可以用作模运(求余)操作符。

print('hello,%s' %'world')
hello,world
print('小智今年%s岁了' %10)
小智今年10岁了

格式化字符串的%s部分称为转换说明符,标记了需要放置转换值的位置,通用术语为占位符。

print('小智今年%d岁了' %10)
#整数既可以使用%s也可以使用%d进行格式化。
小智今年10岁了
#如果要格式化实数(浮点数),就可以使用%f进行格式化。
print('圆周率PI的值为:%f' %3.14)
圆周率PI的值为:3.140000
print('圆周率PI的值为:%.2f' %3.14)
圆周率PI的值为:3.14
print('今年的总收入是去年的%d' %120+'%')
今年的总收入是去年的120%
print('输出百分号:%s' %'%')
输出百分号:%
#字符串格式化元组
print('%d+%d=%d' %(1,1,2))
1+1=2
print('保留2位小数,圆周率PI的值为:%10.2f' %3.14)
# 10表示字段宽度为10
保留2位小数,圆周率PI的值为:      3.14
print('保留2位小数,圆周率PI的值为:%010.2f' %3.14)
# 使用0进行填充
保留2位小数,圆周率PI的值为:0000003.14
print('保留2位小数,圆周率PI的值为:%-10.2f' %3.14)
# -用于左对齐
保留2位小数,圆周率PI的值为:3.14      

2.3字符串常用方法

2.3.1 find()方法

find()方法用于检测字符串中是否包含子字符串str。如果指定beg(开始)和end(结束)范围,就检查是否包含在指定范围内。如果包含子字符串,就返回开始的索引值;否则返回-1。

find()方法的语法如下:
str.find(str, beg=0, end=len(string))

str = "do it now."
str.find('do')
0
str.find('now')
6
str.find('no',1,-1)
6

2.3.2 join()方法

join()方法用于将序列中的元素以指定字符连接成一个新字符串。

join()方法的语法如下:
str.join(sequence)

此语法中,str代表指定检索的字符串,sequence代表要连接的元素序列。返回结果为指定字符连接序列中的元素后生成的新字符串。

num = ['1', '2', '3', '4']
mark = '+'
mark.join(num)
'1+2+3+4'

2.3.3 lower() 、 upper()、swapcase()方法

str = 'Hello World.'
str.lower()
'hello world.'
str.upper()
'HELLO WORLD.'
str.swapcase()
'hELLO wORLD.'

2.3.4 replace()方法

replace()方法把字符串中的old(旧字符串)替换成new(新字符串),如果指定第3个参数max,替换次数就不超过max次。
replace()方法的语法如下:
str.replace(old, new[, max])

str = "I am a student,a good student."
str.replace('student','teacher',1)
'I am a teacher,a good student.'
str = "I am a student,a good student."
str.replace('student','teacher',2)## 2 string(字符串)
'I am a teacher,a good teacher.'

2.3.5 strip()方法

strip()方法用于移除字符串头尾指定的字符(默认为空格)。

strip()方法的语法如下:
str.strip([chars])

str = "--你是个好人--我也是---"
str.strip('-')
'你是个好人--我也是'
M

translate()方法的语法如下:str.translate(table[, deletechars])

此语法中,str代表指定检索的字符串;table代表翻译表,翻译表通过maketrans方法转换而来;deletechars代表字符串中要过滤的字符列表。返回结果为翻译后的字符串。

intab = 'aeiou'
outtab = '12345'
trantab = str.maketrans(intab,outtab)
st = "just do it."
st.translate(trantab)
'j5st d4 3t.'
原文地址:https://www.cnblogs.com/sinlearn/p/12665328.html