Python基础系列——(3)字符串详细介绍

目标:
 认识字符串
 下标
 切片
 常用操作方法

1 认识字符串
字符串是Python中最常用的数据类型,我们一般使用引号来创建字符串。创建字符串很简单,只要为其分配一个变量即可。
例如:

a = 'hello world'
b = "abcdefg"
print(type(a))
print(type(b))

1.1字符串特征

# 一对引号字符串
name1 = 'Tom'
name2 = 'Rose'

# 三引号字符串
name3 = '''Tom'''
name4 = """Rose"""
a = '''i am Tom,
        nice to meet you !'''
print(a)
b = """i am Rose,
        nice to meet you!"""
print(b)
# 三引号形式的字符串支持换行
# 如果创建一个字符串I'm Tom?
c = "I'm Tom"
d = 'I\'m Tom'  # 这里的单引号注意一下!
print(c)
print(d)

1.2 字符串的输入输出

# 字符串的输出
print('hello world')
name = 'Tom'
print('我的名字是%s' % name)
print(f'我的名字是{name}')

# 字符串的输入
# 在Python中,使用input()接收用户输入
password = input('请输入您的密码:')
print(f'您输入的密码是{password}')
print(type(password))

2 下标

下标又叫索引,就是编号。比如火车座位号,座位号的作用:按照编号快速找到对应的座位。
同理:下标的作用即是通过下标快速找到对应的数据。

str1 = 'abc'
print(str1)
"""
1.数据在程序运行过程中存储在内存
2.如何得到数据a字符,b字符等?即如何使用字符串中的某个特定的数据?
3.这些字符数据从0开始顺序分配一个编号---使用这个编号精确找到某个字符数据
下标或索引或索引值
str1[下标]
"""
print(str1[0])
print(str1[1])
print(str1[2])

"""
输出结果:
abc
a
b
c
"""

3 切片

切片是指对操作的对象截取其中一部分的操作。字符串,列表,元组都支持切片操作。
3.1切片语法
序列[开始位置下标:结束位置下标:步长]
注意:
1, 开始,结束下标左闭右开,即不包含结束位置对应的数据,正负数均可。
2, 步长是选取间隔,正负整数均可,默认步长为1.
例子1:

name = "abcdefg"
print(name[2:5:1])  # cde
print(name[2:5])   # cde
print(name[:5])  # abcde
print(name[1:])   # bcdefg

例子2:

# 序列名[开始下标位置:结束下标位置:步长]
str1 = '012345678'
print(str1[2:5:1])   # 234
print(str1[2:5:2])   # 24
print(str1[2:5])    # 234
print(str1[:5])     # 01234---如果不写开始,默认从0开始
print(str1[2:])     # 2345678---如果不写结束,默认选取到最后
print(str1[:])      # 012345678---如果不写开始和结束,表示选取全部

# 负数测试
print(str1[::-1])   # 876543210---步长为负数,表示倒叙选取
print(str1[-4:-1])  # 567---下标-1表示最后一个数据,一次向前类推

# 终极测试 str1 = '012345678'
print(str1[-4:-1:1])    # 567

print(str1[-4:-1:-1])
# 不能选取出数据:从-4开始到-1结束,选取方向从左到右,而步长-1表示从右向左选取
# ***如果选取方向(下标开始到结束的方向)和步长的方向冲突,则无法选取数据

4 常用操作方法

4.1查找
所谓字符串查找方法即是查找子串在字符串中的位置或出现的次数。
 find()—检测某个子串是否包含在这个字符串中,如果在,返回这个子串开始的位置下标,否则返回-1.

# 语法:字符串序列.find(子串,开始下标,结束位置下标)
# 注意:开始,结束位置下标可以省略,表示在整个字符串序列中查找
mystr = "hello world and itcast and itheima and Python"
print(mystr.find('and'))   # 12
print(mystr.find('and', 15, 30))  # 23
print(mystr.find('ands'))  # -1

 index()—检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则报异常。

# 语法:字符串序列.index(子串,开始位置下标,结束下标位置)
# 注意:开始,结束位置下标可以省略,表示在整个字符串序列中查找
mystr = "hello world and itcast and itheima and Python"
print(mystr.index('and'))  # 12
print(mystr.index('and', 15, 30))  # 23
print(mystr.index('ands'))  # 报错

 rfind()—和find()功能相同,但查找方向为右侧开始
 rindex()—和index()功能相同,但查找方向为右侧开始
 count()----返回某个子串在字符串中出现的次数

# 语法:字符串序列.count(子串,开始位置下标,结束下标位置)
# 注意:开始,结束位置下标可以省略,表示在整个字符串序列中查找

例子:

mystr = "hello world and itcast and itheima and Python"
# 1,rfind()
print(mystr.rfind('and'))  # 35
print(mystr.rfind('ands'))  #-1
# 2,rindex()
print(mystr.rindex('and'))  #35
# print(mystr.rindex('ands'))  # 报错
# 3,count()
print(mystr.count('and', 15, 30))  # 1
print(mystr.count('and'))  # 3
print(mystr.count('ands'))  # 0

4.2 修改
所谓修改字符串,指的是通过函数的形式修改字符串中的数据。
4.2.1常用的修改
 replace()----替换

mystr = "hello world and itcast and itheima and Python"
print(mystr.replace('and', 'he'))
# 结果hello world he itcast he itheima he Python
print(mystr.replace('and', 'he', 10))
# 结果hello world he itcast he itheima he Python
print(mystr)
# 结果hello world and itcast and itheima and Python
语法:字符串序列.replace(旧子串,新子串,替换次数)
注意:替换次数如果超出子串出现次数,则替换次数为该子串出现的次数

注意:数据按照是否能直接修改分为可变类型和不可变类型两种。字符串类型的数据修改的时候,不能改变原有的字符串,属于不能直接修改数据的类型,即不可变类型。

 split()----按照指定字符分割字符串
注意:如果分割字符是原有字符串中的子串,分割后则丢失该子串。

mystr = "hello world and itcast and itheima and Python"
print(mystr.split('and'))
# 结果:['hello world ', ' itcast ', ' itheima ', ' Python']
print(mystr.split('and', 2))
# 结果:['hello world ', ' itcast ', ' itheima and Python']
print(mystr.split(' '))
# 结果:['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']
print(mystr.split(' ', 2))
# 结果:['hello', 'world', 'and itcast and itheima and Python']

 join()----用一个字符或子串合并字符串,即是将多个字符串合并为一个新的字符串。

# join语法---字符或子串.join(多字符组成的序列)
mylist = ['aa', 'bb', 'cc']
new_str = '...'.join(mylist)
print(new_str)
# 结果:aa...bb...cc

4.2.2需要了解的修改

 capitalize()----将字符串的第一个字符转换成大写
注意:capitalize()函数转换后,只字符串第一个字符大写,其他的字符均是小写。
 title()----将字符串每个单词首字母转换成了大写。
 lower()----将字符串中大写转小写
 upper()----将字符串中小写转大写
例子:

mystr = "hello world and itcast and itheima and Python"
# 1,解释:将第一个字符转换成大写
#  结果:Hello world and itcast and itheima and python
print(mystr.capitalize())

# 2,解释:将每个单词首字母转成大写
#  结果:Hello World And Itcast And Itheima And Python
print(mystr.title())

# 3,解释:将字符串中的大写转换为小写
#  结果:hello world and itcast and itheima and python
print(mystr.lower())

# 4,解释:将字符串中的小写转大写
#  结果:HELLO WORLD AND ITCAST AND ITHEIMA AND PYTHON
print(mystr.upper())

 删除空白函数
strip()----删除字符串两侧空白符
lstrip()----删除字符串左侧空白符
rstrip()----删除字符串右侧空白符
例子:
在这里插入图片描述
 对齐函数
Ijust()----返回一个原字符串左对齐,并使用指定字符(默认空格)填充至对应长度的新字符串。

# 语法:字符串序列.ljust(长度,填充个字符)

rjust()----返回一个原字符串右对齐,并使用指定字符(默认空格)填充至对应长度的新字符串,语法和ljust()相同。
center()----返回一个原字符串居中对齐,并使用指定字符(默认空格)填充至对应长度的新字符串,语法和ljust()相同。
例子:
在这里插入图片描述

4.3 判断
所谓判断即是判断真假,返回的结果是布尔型数据:True或False
 startswith()—检查字符串是否是以指定子串开头,是则返回True,否则返回False。如果设置开始和结束位置下标,则在指定范围内检查。
语法:
字符串序列.satrtswith(子串,开始位置下标,结束位置下标)
例子:

mystr = "hello world and itcast and itheima and Python"
# 1,startswith():判断字符串是否以某个子串开头
print(mystr.startswith('hello'))
print(mystr.startswith('hel'))
print(mystr.startswith('hels'))

# 2,endswith():判断字符串是否以某个子串结尾
print(mystr.endswith('Python'))
print(mystr.endswith('Pythons'))

 isalpha()—如果字符串至少有一个字符并且所有字符都是字母则返回True,反之。

mystr1 = 'hello'
mystr2 = 'hello12345'
print(mystr1.isalpha())
print(mystr2.isalpha())

 isdigit()—如果字符串只包含数字则返回True,反之。
 isalnum()—如果字符串至少有一个字符并且所有字符都是由字母或数字则返回True,反之。

mystr1 = 'aaa12345'
mystr2 = '12345'
print(mystr1.isdigit())
print(mystr2.isdigit())

print(mystr1.isalnum())
print(mystr2.isalnum())

 isspace()----如果字符串中只包含空白,则返回True,反之。

mystr3 = '1 2 3 4 5'
mystr4 = '     '
print(mystr3.isspace())
print(mystr4.isspace())

关于字符串就介绍这么多,喜欢的小伙伴建议收藏哦!

猜你喜欢

转载自blog.csdn.net/qq_46009608/article/details/109248941