手记

python字符串操作

1、字符串首字母大写

>>> name = "xiaoming"

>>> print(name.capitalize())      //capitalize方法可以使字符串首字母大写

Xiaoming


2、统计字符串中字符的个数

>>> name = "xiaoming"

>>> print(name.count("i"))

2


3、重复打印某个字符

>>> print(name.center(20,"-"))   //总共有20个字符,把"xiaoming"放在中间

------xiaoming------


4、判断字符串以什么结尾

>>> name = "xiaoming"

>>> print(name.endswith("ng"))

True


5、根据字符找索引位置

>>> name = "My name is Xiaoming"

>>> print(name.find("is"))          //find只打印查找到的字符的开头字母的位置

8

>>> print(name[name.find("is"):])     //字符串也支持切片

is Xiaoming


6、字符串格式化输出

>>> name = "My name is {name} and I am {year} years old."

>>> print(name.format(name="Xiaoming",year=20))             //format格式化输出

My name is Xiaoming and I am 20 years old.


>>> print(name.format_map( {"name":"Xiaoming","year":25} ))     //format_map可以以字典的格式进行传输

My name is Xiaoming and I am 25 years old.


7、判断字符串是不是纯英文字符组成

>>> name = "abc"

>>> print(name.isalpha())

True

>>> name = "ab12"

>>> print(name.isalpha())

False


8、判断数字是不是整数

>>> print("aa".isdigit())

False

>>> print("11".isdigit())

True

>>> print("11.2".isdigit())

False


9、判断字符串是不是小写

>>> name = "abc"

>>> print(name.islower())

True

>>> name = "My"

>>> print(name.islower())

False


10、判断字符串中的字符开头是不是大写字母

>>> name = "my name"

>>> print(name.istitle())

False

>>> name = "My Name"

>>> print(name.istitle())

True


11、判断字符串是不是全是大写字母

>>> name = "MY NAME"

>>> print(name.isupper())

True


12、join的简单使用

>>> print("".join(["1","2","3"]))

123

>>> print("+".join(["1","2","3"]))

1+2+3


13、ljust()和rjust()的使用

>>> name

'MY NAME'

>>> print(name.ljust(20,"*"))    //注意:是整个字符串共长20,"MY NAME"共长7,所以"*"只有13个

MY NAME*************

>>> print(name.rjust(20,"*"))

*************MY NAME


14、字符串的大小写转换

>>> name

'MY NAME'

>>> print(name.lower())      //lower是把大写变成小写

my name

>>> print(name.upper())      //upper是把小写转换为大写

MY NAME


15、去除字符串两头的回车或者空格

>>> print("\nMy name")


My name

>>> print("\nMy name".lstrip())     //lstrip为去除字符串左边的空格或回车

My name

>>> print("My name\n")

My name


>>> print("My name\n".rstrip())    //rstrip为去除字符串右边的空格或回车

My name


>>> print("\nMy name\n".strip())   //strip为去除两头的空格或回车

My name


16、字符的替换

>>> print("abca".replace("a","L"))        //默认为全部替换

LbcL

>>> print("abca".replace("a","L",1))       //可以指定

Lbca


17、字符串分割成列表

>>> print("My name is Xiaoming".split())      //默认为空格

['My', 'name', 'is', 'Xiaoming']

>>> print("My name is Xiaoming".split("i"))    //可以指定分隔符

['My name ', 's X', 'aom', 'ng']


18、swapcase,把字符串中的小写转大写,大写转小写

>>> print("My name is".swapcase())

mY NAME IS


0人推荐
随时随地看视频
慕课网APP