Python字符串常用方法(二)

2022-12-07,,,

二、字符串的操作常用方法

字符串的替换、删除、截取、复制、连接、比较、查找、分割等

1. string. lower() :转小写

2. string. upper() :转大写

3. string.strip([chars]) :去除括号字符

4. string.lstrip() : 截掉 string 左边的空格

5. string.rstrip() : 删除 string 字符串末尾的空格.

6.string.title(): 返回"标题化"的 string,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())

7. string.swapcase() 翻转 string 中的大小写

8.string.count() 统计字符出现的次数

name = 'xiaoming' name_num = name.count('i') print(name_num) # 2

9. string.center()让字符串放在中间

#打印输出字符,让字符串放在中间 name = 'Libai' print(name.center(50,'*'))

输出结果如下:

**********************Libai***********************

10.sting.format()

String.format() 输出指定的内容

user_show_name = 'hello,{name},welcome to here,do you like ,{name}' print(user_show_name.format(name='yanyan'))

输出效果如下:

hello,yanyan,welcome to here,do you like ,yanyan

name.format_map(d)  字符串格式化,传进去的是一个字典

11.string. join()

sep.join(seq) 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串

# 创建一个列表 name = ['张学友','刘德华','郭富城','黎明'] print('--'.join(name))

输出结果如下:

张学友--刘德华--郭富城--黎明

12. string.replace 替换

String.replace(old,new,count) 将字符串中的old字符替换为New字符,count为替换的个数

str = 'hello,world,hello' print(str.replace('hello','Hello',1))

输出的效果如下:

Hello,world,hello

13. String.split() 切割

str = 'hello,world,hello' # 默认以空格为分割 print(str.split()) # ['hello,world,hello'] 单词之间没有空格,所以所有的内容为一个元素 # 以o为分割 print(str.split('o')) # ['hell', ',w', 'rld,hell', ''] # 以逗号分割 print(str.split(',')) # ['hello', 'world', 'hello']

14.string.capitalize()

String.capitalize() 将字符串首字母变为大写

name = 'xiaoming' new_name = name.capitalize() print(new_name)

运行结果:

Xiaoming

注:

Python中capitalize()与title()的区别

capitalize()与title()都可以实现字符串首字母大写.

主要区别在于:

capitalize(): 字符串第一个字母大写

title(): 字符串内的所有单词的首字母大写

例如:

>>> str='huang bi quan' >>> str.capitalize() 'Huang bi quan' #第一个字母大写 >>> str.title() 'Huang Bi Quan' #所有单词的首字母大写

非字母开头的情况:

>>> str='深圳luohu' >>> str.capitalize() '深圳luohu' #输出内容不变 >>> str.title() '深圳Luohu' #第一个字母大写

Python字符串常用方法(二)的相关教程结束。

《Python字符串常用方法(二).doc》

下载本文的Word格式文档,以方便收藏与打印。