python 字符串1_1

116 阅读1分钟

介绍

字符串类型: str

作用:记录描述性质的数据,比如人的名字、性别、家庭地址、公司简介......

定义:在引号内按照从左到右的顺序依次包含一个个字符,引号可以是单引号、双引号、三引号

a = '张三'
b = "李四"
c = '''王五'''
# 张三 李四 王五
print(a, b, c)

1、常用操作+内置的方法

优先掌握的操作:

1、按索引取值(正向取+反向取):只能单个取, [索引值]

索引相当于书本的页码, 索引是从 0 开始

# 正向取
str1 = 'hello python'
# h
print(str1[0])

# ===================

# 反向去
str1 = 'hello python'
# n
print(str1[-1])

字符串类型,根据索引值修改是不可以的, 字符串是不可变类型

强行用索引修改会报错

str1 = 'hello python'
str1[0] = 'H'
# TypeError: 'str' object does not support item assignment
print(str1)

只能用方法进行修改。

2、切片:多个取, [起始值:终止值:步长]

切片(顾头不顾尾,步长)查找列表当中的一段值 [起始值:终止值:步长]

相当于切黄瓜一节一节

不顾尾, 所以正步长终止值是要查找位置的索引值+1,负步长终止值是要查找位置的索引值-1

步长 默认值 1, 意思是取值时跨1步去取

str1 = 'hello python'
# hello
print(str1[0: 5])

==================

str1 = 'hello python'
# hlo
print(str1[0: 5: 2])

负数步长

str1 = 'hello python'
# nohtyp
print(str1[11: 5: -1])

3、长度len方法 可以计算长度

len(字符串)

str1 = 'hello python'
# 12
print(len(str1))