python之字符串常用的方法

1. 去掉空格或换行符

s='. hello .world .\n'
new_s = s.strip()#默认去掉字符串前后的空格和换行符
new_s = s.strip('.')#可传参去掉字符串前后指定的参数
print(new_s)
print(s.rstrip()) #去掉右字符串后的空格和换行符
print(s.lstrip()) #去掉左字符串前的空格和换行符


输出结果如下:
 hello .world .

. hello .world .
. hello .world .

==========================

2. 输出指定字符串的出现次数

print(s.count('l')) #3

3. 找字符串的下标
区别:index查找不存在的字符串时会报错;find会返回-1

print(s.find('l'))   #4
print(s.index('l')) #4  如查找不存的字符串会报错:ValueError: substring not found

4. 替换字符串:Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

print(s.replace('l','L')) #将字符串中所有小写l替换成大写L,输出:. heLLo .worLd .
print(s.replace('l','L',2)) #将字符串中前2个小写l替换成大写L,输出:. heLLo .world .

 

5. 将字符串全部转换成大写或小写

print(s.upper()) #将字符串全部转换成大写,输出:. HELLO .WORLD .
print(s.lower()) #将字符串全部转换成小写,输出:. hello .world .

6. 判断字符串是否都是大写或小写,返回布尔值类型

# 返回True 或者 False
print(s.isupper())  
print(s.islower())

7. 首字母大写,注意,第一个字符必须是字母才生效

s='hello .world .\n'
print(s.capitalize())  #输出:Hello .world .

8. 检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写。

#返回True 或者 False
print(s.istitle())

 

9.  判断字符串是否以某个字符开始、结束,返回布尔值类型。可运用于如,判断用户上传的图片格式是否以.png结束,格式是否正确

# 返回True 或者 False
print(s.startswith('h'))
print(s.endswith('\n'))

10. 判断字符串是否为纯数字,返回布尔值,可用于输入框文本类型的校验

#返回True 或者 False
s1='123test'
print(s1.isdigit())

11. 判断字符串中是否都是字母或汉字,不能有数字和特殊字符,返回布尔值

#返回True 或者False
s2='我test'
print(s2.isalpha())

12. 判断字符串里只要没有特殊字符就返回true

#返回True 或者 False
s2='我test123'
print(s2.isalnum())

13. 把字符串放中间,不够的可用后面指定的字符串补齐

# 可指定需要用什么字符补齐,也可留空,显示为空格
s1='123test'
print(s1.center(30,'-')) 

输出:
-----------123test------------

14. 判断字符串是否都是空格组成,可用于非空校验

#返回True 或者 False
print(s.isspace())

15. 判断是否是数字,字母,下划线开头,是否是标准的变量名,是否尊循了变量命名规范,不能以数字和特殊字符开头,返回布尔

#返回True 或者False
s2='我test123'
print(s2.isidentifier())

16. fomat:不用按字符串顺序去一一对应的录入数据,数据库,不同于%s得一一对应

s1 = 'insert into user-base VALUE ({username},{password},{addr});'
print(s1.format(addr='北京',password=159,username='abc'))

输出:
insert into user-base VALUE (abc,159,北京);

17. zfill(): 补0

s2='1'
print(s2.zfill(3))  #输出:001

18. split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串,num指分割次数

s='user1,user2,user3,user4,user5,user6,user7'
print(s.split(','))#按照某个字符来分割一个字符串,返回一个list

#输出:
['user1', 'user2', 'user3', 'user4', 'user5', 'user6', 'user7']

print(s.split())#什么都不传的话按照空格来分割字符串,没有空格就整体是一个元素
#输出:
['user1,user2,user3,user4,user5,user6,user7']
str = "Line1-abcdef \nLine2-abc \nLine4-abcd"

print(str.split( ))
#输出:['Line1-abcdef', 'Line2-abc', 'Line4-abcd']

print(str.split(' ', 1))
#输出:['Line1-abcdef', '\nLine2-abc \nLine4-abcd']

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

cars=['BMW','BEN','ABC']
res=','.join(cars)#以某个字符(随意指定)把list里面的元素连起来,把list变成字符串
print(res)  
#输出:BMW,BEN,ABC

cars_str= str(cars)
print('第一个元素是:',cars_str[0])
#也可以变成字符串,但是直接从在[开始取值
#输出:
第一个元素是: [

猜你喜欢

转载自www.cnblogs.com/denise1108/p/9989941.html