python 字符串

1.字符串中r字母的作用
print('c:\northwind\northwest')
print('c:\\northwind\\northwest')
print(r'c:\northwind\northwest') # 在字符串前面加入r,就不是一个普通字符串,而是一个原始字符串(即所见即所得,没有转义的成分在其中)

2.字符串常用内置函数用法

2.1 capitalize()函数 将字符串的首字母大写,其他字母小写

name = "xiaoMu"
new_name = name.capitalize()
print(new_name)

capitalize()函数的注意事项:

1.只对第一个字母有效  例子:number_message = '1ok' 

2.只对字母有效         例子:chinese = '你好,小穆'

3.已经是大写,则无效  例子:had_big = 'Good'

2.2 字符串小写函数 casefold() 和 lower()

2.3 字符串大写函数 upper()

2.4 字符串字母大小写翻转方法swapcase()

name = "xiaoMu"
new_name = name.swapcase()
print(new_name)

2.5 字符串zfill() 填充0方法

name = "xiaomu"
new_name = name.zfill(10)
print(new_name) #0000xiaomu

zfill() 注意事项:

与字符串的字符无关

如果定义长度小于当前字符串长度,则不会发生变化

test_str = 'my name is dewei'
new_str = test_str.zfill(5)
print(new_str) # my name is dewei

2.6 字符串count()方法

info = 'my name is dewei'
print(info.count('e')) # 字母e出现了三次

2.7 startswith() 和 endswith()

startwith 判断字符串开始位是否是某成员(元素)

endswith 判断字符串结尾是否是某成员(元素)

info = 'my name is dewei'
print(info.startswith('my')) # True
print(info.endswith('my'))  # False

2.8 字符串find函数 和 index 函数 

find函数和index函数都是获取某个值位置的方法。

find函数找不到返回-1,index函数找不到返回错误。

info = 'my name is dewei'
print(info.find('e')) # 6
print(info.index('i'))  # 8

2.9 字符串strip 函数,lstrip,rstrip 左右去空格方法

strip 函数去掉字符串左右两边的元素,默认是去掉空格。

lstrip 函数仅仅去掉字符串开头的指定的元素或空格

rstrip 函数仅仅去掉字符串结尾的指定的元素或空格

name = "  hxiaomuh  "
new_name1 = name.strip()
print(new_name1)
name = "hxiaomuh"
new_name2 = name.strip('h')
print(new_name2) 

2.10 字符串替换方法 replace()

replace() 是指将字符串中某些旧的元素替换成新的元素,并能指定替换的数量。

2.11 bool类型函数方法集合

isspace istitle isupper islower join split 方法。

isspace 判断字符串是否是由一个空格组成的字符串。ps:由空格组成的字符串,不是空字符串

istitle 判断字符串是否是一个标题类型。

isupper 判断字符串中的字母是否都是大写。

isupper 判断字符串中的字母是否都是小写。

ps:只检测字符串里面的字母,对其他字符不做判断。

extend函数的用法

students = ['a','b','c','d']
new_students = ['e','f']
students.extend(new_students)
print(students) #['a', 'b', 'c', 'd', 'e', 'f']

posted @ 2022-05-27 15:18  repinkply  阅读(12)  评论(0)    收藏  举报