python学习(5)字符串操作函数

python常用字符串操作函数:

1.大小写互转

print('hello World'.swapcase())

HELLO wORLD

2.字符串填充

print('hello World'.center(13,'*'))
print('hello World'.ljust(13,'*'))
print('hello World'.rjust(13,'*'))

hello World
hello World**
**hello World

3.字符计数

print('hello World'.count('o'))

4.字符串开始结尾判断

print('hello World'.endswith('d'))
print('hello World'.startswith('h'))

5.查找字符串返回索引

print('hello World'.find('o'))

6.字符串替换

print('hello World'.replace('h','w'))

7.字符映射实现简单加密

in_str = 'abcxyz'
out_str = '123456'
# maketrans()生成映射表
map_table = str.maketrans(in_str, out_str)
print(map_table)
# 使用translate()进行映射
my_love = 'I love fairy'
result = my_love.translate(map_table)
print(result)

{97: 49, 98: 50, 99: 51, 120: 52, 121: 53, 122: 54}
I love f1ir5

8.字符串分割

print('abcxyzxyopq'.partition('xy'))
print('abcxyzxyopq'.rpartition('xy'))

9.字符串拆分

print('abcxyzxyopq'.split('xy'))

10.字符串连接

print('#'.join('abcxyzxyopq'))

11.字符串修剪

print(' abcxyzxyopq '.strip())
print('www.baidu.com'.strip('cmowz.'))

python学习(5)字符串操作函数_第1张图片

8小时Python零基础轻松入门

你可能感兴趣的:(python学习)