字符串是用来存储一组有序的字符数据,但其中的内容不可修改(只能查,不能增删改)。
字符串和列表、元组一样,也支持下标。
msg = 'welcome to taiyuan'
print(msg[1])
print(msg[-1])
使用字符串.index(字符),获取指定字符在字符串中第一次出现的下标,返回值:下标。
msg = 'welcome to taiyuan'
result = msg.index('t')
print(result)
使用字符串.split(字符),将字符串按照指定字符进行分隔,返回值:列表。
day = '2026-03-18'
result = day.split('-')
print(result, type(result)) # ['2026', '03', '18'] <class 'list'>
print(day) # 2026-03-18
使用字符串.replace(被替换的字符串片段,目标字符串),将字符串中被替换的字符串替换成目标字符串,不会修改原字符串,返回新字符串。
msg = 'welcome to taiyuan'
result = msg.replace('taiyuan', '太原')
print(result) # welcome to 太原
print(msg) # welcome to taiyuan
使用字符串.count(字符),统计指定字符在字符串中出现的次数。
msg = 'welcome to taiyuan'
result = msg.count('o')
print(result) # 2
使用字符串.strip(字符),从某个字符串中删除指定字符串中的任意字符,不会不会修改原字符串,返回值:新字符串。删除规则是:从字符串的两端开始删除,直到遇到第一个不在指定字符串中的字符就停止。
# 删除两端的
msg1 = '666尚6硅6谷6666'
result = msg1.strip('6')
print(result) # 尚6硅6谷
# 删除两端的,与字符顺序无关
msg2 = '1234尚12硅34谷3412'
result = msg2.strip('1324')
print(result) # 尚12硅34谷
# 删除两端的,遇到第一个不在strip方法参数指定的字符串字符就停止
msg3 = '34215尚12硅34谷4132'
result = msg3.strip('5432')
print(result) # 15尚12硅34谷41
注意:如果 strip() 的参数省略或为None,则会删除两端的空白。
msg4 = ' 尚硅谷 '
result = msg4.strip()
print(result) # 尚硅谷
print(msg4) # 尚硅谷
result = msg4.strip(None)
print(result) # 尚硅谷
print(msg4) # 尚硅谷
Python还有更多好玩的方法,请阅读官方手册:https://docs.python.org/zh-cn/3.13/library/stdtypes.html#string-methods
字符串也可以使用:max()、min()、len()、sorted() 等函数,但实际开发中 len() 最常用。
使用len(字符串)获取字符串中的字符的个数(字符串长度)。
msg1 = '12345'
print(len(msg1)) # 5
msg2 = 'abcd'
print(len(msg2)) # 4
msg3 = '大龄程序员'
print(len(msg3)) # 5
注意:一个数据或一个字母代表长度1,一个汉字也代表长度1。
学习更多内置函数,请阅读官方手册:https://docs.python.org/zh-cn/3.13/library/functions.html#len
字符串与列表、元组一样,也可以使用 while 或 for 来循环遍历。
# 使用while遍历字符串
words = 'welcome'
index = 0
while index < len(words):
print(words[index])
index += 1
print() # 换行
# 使用for遍历字符串
for letter in words:
print(letter)
🔥BuildAdmin是一个永久免费开源,无需授权即可商业使用,且使用了流行技术栈快速创建商业级后台管理系统。