iOS开发人员如何学习Python编程5-数据类型2
这是我参与11月更文挑战的5天,活动详情查看:2021最后一次更文挑战。
字符串
字符串是Python
中最常用的数据类型之一,使用单引号
或双引号
来创建字符串,使用三引号
创建多行字符串。
字符串是不可变的序列数据类型,不能直接修改字符串本身,和数字类型一样。所以当我们要从"hello world"
当中取出某一个字母就需要通过索引(默认从0开始)来取:
```
s1 = "hello world"
s1[1]
'e' s1[10] 'd' s1[-1] 'd' s1[11] Traceback (most recent call last): File "", line 1, in IndexError: string index out of range ``` ⚠️注意:字符串是不可变数据类型。
字符串切片(slice
)
输入help(slice)
,查看切片说明文档:
slice(start, stop[, step])
- start
起始位置,默认索引从0开始
- stop
结束位置,默认最后一个元素
- step
步长,默认为1
1. 从"hello world"
取出world
值:
```
s3 = "hello world" s3[6:10] # 注意,左闭右开 'worl' s3[6:11] 'world' s3[6:] # 不写默认取到最后一位 'world' ```
- 逆序输出:
```
s3[::-1] 'dlrow olleh' ```
- 将字符串转为整数类型:
```
int('1') 1 ```
- 将整数类型转为字符串:
```
str(1) '1' ```
- 拼接字符串:
print('1'+'2') # 12
- 格式化字符串:\
%s %d %f
: \str.format()
: \ 简写str.format
:
name = 'cat'
age = 18
print('%s年龄%d'%(name,age))
name = 'cat'
age = 18
print('{}年龄{}'.format(name,18))
print('{1}年龄{0}'.format(18,name))
name = 'cat'
age = 18
print(f'{name}的年龄是{age}')
字符串常用方法
S.find(sub)
返回该元素最小的索引:
```
s4 = 'hello python' s4.find('e') 1 s4.find('o') # 当元素有多个时,返回最小索引 4 s4.find('c') # 找不到则为-1 -1 ```
S.index(sub)
返回该元素最小的索引,该方法与s.find()
实现的功能一样,但是唯一不同的就是当元素不存在时,s.index()
方法会报错。所以建议使用s.find()
。S.replace(old, new[, count])
替换: ```s5 = "hello python" s5.replace('l','a') # 将'l'替换成'a',全部替换 'heaao python'
s5 'hello python' # 注意:原来的字符串并没有被改变
s5.replace('l','a',1) # 只替换一个,则指定count参数为1即可 'healo python' ```
S.split(sep=None)
以sep
来分割字符串,并返回列表。sep
默认为None
,分割默认为空格:
```
s6 = 'hello everyboby ye!' s6.split(' ') ['hello', 'everyboby', 'ye!'] ```
S.startswith(prefix[, start[, end]])
判断字符串是否以前缀开始,返回为bool
值:
```
s7 = "hello world" s7.startswith("he") True ```
S.endswith(suffix[, start[, end]])
判断字符串是否以尾缀结束,返回为bool
值:
```
s7 'hello world' s7.endswith('ld') True
`` 7.
S.lower()将字符串全部转为小写。 8.
S.upper()将字符串全部转为大写。 9.
S.strip([chars])`默认去掉字符串左右的空格:
```
s8 = ' hello world ' s8.strip() 'hello world' ```
S.isalpha()
判断字符串是否全为字母,返回的是bool
值。S.isdigit()
判断字符串是否全为数字,返回的是bool
值。S.isalnum()
判断字符串是否全为数字或者字母,不存在特殊字符,返回的是bool
值。S.join(iterable)
将序列中的元素以指定的字符连接生成一个新的字符串。