19-python中字符串相关,切片以及str常用的方法

1. 认识字符串

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

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

注意:控制台显示结果为 <class 'str'> , 即数据类型为str(字符串)。

1 字符串特征

1. 一对引号字符串

name1 = 'Tom'
name2 = "Rose"

2. 三引号字符串

name3 = ''' Tom '''
name4 = """ Rose """
a = ''' i am Tom,
nice to meet you! '''
b = """ i am Rose,
nice to meet you! """

注意:三引号形式的字符串支持换行。

2. 思考:如果创建一个字符串 I'm Tom ?

c = "I'm Tom"
d = 'I\'m Tom'


print(c)
print(d)

2. 字符串切片

切片是指对操作的对象截取其中一部分的操作。 字符串、列表、元组都支持切片操作。

1. 切片的语法

序列[开始位置下标:结束位置下标:步长]

  1. 不包含结束位置下标对应的数据, 正负整数均可;
  2. 步长是选取间隔,正负整数均可,默认步长为1。

2. 实际的例子

1. 正数

不写开始,默认从0开始
不写结束,表示选取到最后
默认步长是1

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

2. 负数

name = "abcdefg"

for i in range(-1, -8, -1):
    print(f"name[{i}]: {name[i]}")

输出:

name[-1]: g
name[-2]: f
name[-3]: e
name[-4]: d
name[-5]: c
name[-6]: b
name[-7]: a

步长是负数的时候表示从右侧往左侧选,倒着选

name = "abcdefg"

#print(name[::-1]) #gfedcba, 步长是负数,表示倒序
print(name[-4:-1:]) # def

print(name[-4:-1:-1]) # 这个是选不到任何东西的
#因为 -4 —— -1 方向是从左到右选取,而 -1 代表右侧往左侧选,倒着选 两个方向相反,选不到任何东西

3. 如果选取方向(下标开始到结束的方向) 和步长的方向冲突,则无法选取数据

3. 字符串常用的方法

2. 修改

所谓修改字符串串,指的就是通过函数的形式修改字符串串中的数据。

1. replace():替换

1. 语法

字符串串序列列.replace(旧⼦子串串, 新⼦子串串, 替换次数)

注意:替换次数如果超出⼦子串串出现次数,则替换次数为该⼦子串串出现次数。

2. 快速体验

mystr = "hello world and itcast and itheima and Python"

# 结果: hello world he itcast he itheima he 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 and Python
print(mystr.replace('and', 'he', 2))

# 结果: hello world and itcast and itheima and Python
print(mystr)

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

2. split():按照指定字符分割字符串串。

1. 语法

split返回的是分割好的 列表

字符串串序列列.split(分割字符, num)

注意: num表示的是分割字符出现的次数,即将来返回数据个数为num+1个。

2. 快速体验

mystr = "hello world and itcast and itheima and Python"


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


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


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


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

注意:如果分割字符是原有字符串串中的⼦子串串,分割后则丢失该⼦子串串。

3. join():⽤用⼀一个字符或⼦子串串合并字符串串,即是将多个字符串串合并为⼀一个新的字符串串。

1. 语法

字符或⼦子串串.join(多字符串串组成的序列列)

2. 快速体验

list1 = ['chuan', 'zhi', 'bo', 'ke']
t1 = ('aa', 'b', 'cc', 'ddd')

# 结果: chuan_zhi_bo_ke
print('_'.join(list1))

# 结果: aa...b...cc...ddd
print('...'.join(t1))

猜你喜欢

转载自blog.csdn.net/sgy1993/article/details/114971411