Python处理字符串有很多常用函数
判断某子串是否在字符串里:
1. 使用成员操作符in
Str = 'Hello, world!\n' sStr = '\n' result = sStr in Str print(result) # True
2. 使用字符串的find()、index()火count()方法
Str = 'Hello, world!\n' sStr = '\n' result = Str.find(sStr) >= 0 print(result) # True result = Str.count(sStr) > 0 print(result) # True result = Str.index(sStr) >= 0 print(result) # True
字符串分隔
使用split()
Str = 'Hello, world!\n' Str1, Str2 = Str.split(',') print(Str1) # Hello print(Str2) # world! sStr = Str.split(',') print(sStr) # ['Hello', ' world!\n']
如果用一个对象来作为splt()的返回值,则是一个包含这两个子字符串的list。
判断字符串中是否只是数字
1. 可以使用isdigit()函数,但有的时候数字是用逗号','隔开的,我希望判断隔开后的是不是只有数字
Str = '3,5' result = Str.isdigit() print(result) # False sStr1,sStr2 = Str.split(',') result = sStr1.isdigit() print(result) # True
2. 然而有时候字符串里有负数,这样可以先用strip()函数把'-'去掉,再做判断
Str = '-3,5' result = Str.isdigit() print(result) # False sStr1,sStr2 = Str.split(',') result = sStr1.isdigit() print(result) # False result = sStr1.strip('-').isdigit() print(result) # True
将字符串转换为数字
可以用int()转换成整型,用float()转换成浮点型
Str = '3,5.2' sStr1, sStr2 = Str.split(',') result = int(sStr1) print(result) # 3 result = float(sStr2) print(result) # 5.2
参考:https://blog.youkuaiyun.com/yl2isoft/article/details/52079960