在Python中,字符串属于不可变序列类型,除了支持序列通用方法(包括分片操作)以外,还支持特有的字符串操作方法。
Python字符串驻留机制:对于短字符串,将其赋值给多个不同的对象时,内存中只有一个副本,多个对象共享该副本。长字符串不遵守驻留机制。
常用格式字符
格式字符 | 说明 |
%s | 字符串 (采用str()的显示) |
%r | 字符串 (采用repr()的显示) |
%c | 单个字符 |
%d | 十进制整数 |
%i | 十进制整数 |
%o | 八进制整数 |
%x | 十六进制整数 |
%e | 指数 (基底写为e) |
%E | 指数 (基底写为E) |
%f、%F | 浮点数 |
%g | 指数(e)或浮点数 (根据显示长度) |
%G | 指数(E)或浮点数 (根据显示长度) |
%% | 一个字符"%" |
使用format方法进行格式化
>>> print("The number {0:,} in hex is: {0:#x}, the number {1} in oct is {1:#o}".format(5555,55))
The number 5,555 in hex is: 0x15b3, the number 55 in oct is 0o67
>>> print("The number {1:,} in hex is: {1:#x}, the number {0} in oct is {0:o}".format(5555,55))
The number 55 in hex is: 0x37, the number 5555 in oct is 12663
#最常用
>>> print("my name is {name}, my age is {age}, and my QQ is {qq}".format(name = "Dong Fuguo",age = 40,qq = "30646****"))
my name is Dong Fuguo, my age is 40, and my QQ is 30646****
>>> position = (5, 8, 13)
>>> print("X:{0[0]};Y:{0[1]};Z:{0[2]}".format(position))
X:5;Y:8;Z:13
>>> name = 'Dong'
>>> age = 39
>>> f'My name is {name}, and I am {age} years old.'
'My name is Dong, and I am 39 years old.'
find()、rfind()、index()、rindex()、count()
find()和rfind方法分别用来查找一个字符串在另一个字符串指定范围(默认是整个字符串)中首次和最后一次出现的位置,如果不存在则返回-1;
index()和rindex()方法用来返回一个字符串在另一个字符串指定范围中首次和最后一次出现的位置,如果不存在则抛出异常;
count()方法用来返回一个字符串在当前字符串中出现的次数。
split()、rsplit()、partition()、rpartition()
split()和rsplit()方法分别用来以指定字符为分隔符,把当前字符串从左往右或从右往左分隔成多个字符串,并返回包含分隔结果的列表;
partition()和rpartition()用来以指定字符串为分隔符将原字符串分隔为3部分,即分隔符前的字符串、分隔符字符串、分隔符后的字符串,如果指定的分隔符不在原字符串中,则返回原字符串和两个空字符串。
字符串连接join()
不推荐使用+运算符连接字符串,优先使用join()方法。
>>> li = ["apple", "peach", "banana", "pear"]
>>> ','.join(li)
'apple,peach,banana,pear'
>>> '.'.join(li)
'apple.peach.banana.pear'
>>> '::'.join(li)
'apple::peach::banana::pear’
>>#对目录进行操作
>> import os
>>os.path.join(‘/dev/’,’python’,’chapter1')
hello/good/date/datbody
lower()、upper()、capitalize()、title()、swapcase()
>>> s = "What is Your Name?"
>>> s.lower() #返回小写字符串
'what is your name?'
>>> s.upper() #返回大写字符串
'WHAT IS YOUR NAME?'
>>> s.capitalize() #字符串首字符大写
'What is your name?'
>>> s.title() #每个单词的首字母大写
'What Is Your Name?'
>>> s.swapcase() #大小写互换
'wHAT IS yOUR nAME?'
查找替换replace(),类似于Word中的“全部替换”功能。
>>> s = "中国,中国"
>>> print(s)
中国,中国
>>> s2 = s.replace("中国", "中华人民共和国") #两个参数都作为一个整理
>>> print(s2)
中华人民共和国,中华人民共和国
strip()、rstrip()、lstrip()
>>> s = " abc "
>>> s.strip() #删除空白字符
'abc'
>>> '\n\nhello world \n\n'.strip() #删除空白字符
'hello world'
>>> "aaaassddf".strip("a") #删除指定字符
'ssddf'
>>> "aaaassddf".strip("af")
'ssdd'
>>> "aaaassddfaaa".rstrip("a") #删除字符串右端指定字符
'aaaassddf'
>>> "aaaassddfaaa".lstrip("a") #删除字符串左端指定字符
'ssddfaaa'
成员判断,关键字in
>>> "a" in "abcde" #测试一个字符中是否存在于另一个字符串中
True
>>> 'ab' in 'abcde'
True
>>> 'ac' in 'abcde' #关键字in左边的字符串作为一个整体对待
False
>>> "j" in "abcde"
False
Python字符串支持与整数的乘法运算,表示序列重复,也就是字符串内容的重复,得到新字符串。
>>> 'abcd' * 3
'abcdabcdabcd'
s.startswith(t)、s.endswith(t),判断字符串是否以指定字符串开始或结束
>>> s = 'Beautiful is better than ugly.'
>>> s.startswith('Be') #检测整个字符串
True
>>> s.startswith('Be', 5) #指定检测范围起始位置
False
>>> s.startswith('Be', 0, 5) #指定检测范围起始和结束位置
True
>>> import os
>>> [filename
for filename in os.listdir(r'c:\\')
if filename.endswith(('.bmp','.jpg','.gif'))]
center()、ljust()、rjust(),返回指定宽度的新字符串,原字符串居中、左对齐或右对齐出现在新字符串中,如果指定宽度大于字符串长度,则使用指定的字符(默认为空格)进行填充。
>>> 'Hello world!'.center(20) #居中对齐,以空格进行填充
' Hello world! '
>>> 'Hello world!'.center(20, '=') #居中对齐,以字符=进行填充
'====Hello world!===='
>>> 'Hello world!'.ljust(20, '=') #左对齐
'Hello world!========'
>>> 'Hello world!'.rjust(20, '=') #右对齐
'========Hello world!'
isalnum()、isalpha()、isdigit()、isdecimal()、isnumeric()、isspace()、isupper()、islower(),用来测试字符串是否为数字或字母、是否为字母、是否为数字字符、是否为空白字符、是否为大写字母以及是否为小写字母。
>>> '1234abcd'.isalnum()
True
>>> '1234abcd'.isalpha() #全部为英文字母时返回True
False
>>> '1234abcd'.isdigit() #全部为数字时返回True
False
>>> 'abcd'.isalpha()
True
>>> '1234.0'.isdigit()
False
切片也适用于字符串,但仅限于读取其中的元素,不支持字符串修改。
>>> 'Explicit is better than implicit.'[:8]
'Explicit'
>>> 'Explicit is better than implicit.'[9:23]
'is better than'
例:
#1、测试用户输入中是否有敏感词,如果有的话就把敏感词替换为3个星号***并输出。
敏感词:words = (‘毒品’, ‘非法’, ‘暴力’, ‘色情’)
i_string = input()
words = ('色情','暴力','非法')
for i in words:
i_string = i_string.replace(i,'***')
print(i_string)
#2、生成6位随机数,每位随机数可以是大小写字符或数字。
提示:可以使用random. choice()。
s_string = ''
for i in range(6):
s_string += random.choice(string.digits.join(string.ascii_letters))
print(s_string)