iOS开发人员如何学习Python编程5-数据类型2

语言: CN / TW / HK

这是我参与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' ```

  1. 逆序输出: 

```

s3[::-1] 'dlrow olleh' ```

  1. 将字符串转为整数类型: 

```

int('1') 1 ```

  1. 将整数类型转为字符串: 

```

str(1) '1' ```

  1. 拼接字符串: 

print('1'+'2') # 12

  1. 格式化字符串:\ %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}')

字符串常用方法

  1. S.find(sub) 返回该元素最小的索引: 

```

s4 = 'hello python' s4.find('e') 1 s4.find('o') # 当元素有多个时,返回最小索引 4 s4.find('c') # 找不到则为-1 -1 ```

  1. S.index(sub)返回该元素最小的索引,该方法与s.find()实现的功能一样,但是唯一不同的就是当元素不存在时,s.index()方法会报错。所以建议使用s.find()。 
  2. 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' ```

  1. S.split(sep=None)sep来分割字符串,并返回列表。sep默认为None,分割默认为空格: 

```

s6 = 'hello everyboby ye!' s6.split(' ') ['hello', 'everyboby', 'ye!'] ```

  1. S.startswith(prefix[, start[, end]])判断字符串是否以前缀开始,返回为bool值: 

```

s7 = "hello world" s7.startswith("he") True ```

  1. 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' ```

  1. S.isalpha() 判断字符串是否全为字母,返回的是bool值。 
  2. S.isdigit()判断字符串是否全为数字,返回的是bool值。 
  3. S.isalnum()判断字符串是否全为数字或者字母,不存在特殊字符,返回的是bool值。 
  4. S.join(iterable)将序列中的元素以指定的字符连接生成一个新的字符串。