Python 字符串处理常用函数
2018-07-28 15:49
369 查看
版权声明:转载请声明 https://blog.csdn.net/qq_23141851/article/details/81261341
Python处理字符串有很多常用函数
判断某子串是否在字符串里:
1. 使用成员操作符in
[code]Str = 'Hello, world!\n' sStr = '\n' result = sStr in Str print(result) # True2. 使用字符串的find()、index()火count()方法
[code]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()
[code]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()函数,但有的时候数字是用逗号','隔开的,我希望判断隔开后的是不是只有数字
[code]Str = '3,5' result = Str.isdigit() print(result) # False sStr1,sStr2 = Str.split(',') result = sStr1.isdigit() print(result) # True2. 然而有时候字符串里有负数,这样可以先用strip()函数把'-'去掉,再做判断
[code]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()转换成浮点型
[code]Str = '3,5.2' sStr1, sStr2 = Str.split(',') result = int(sStr1) print(result) # 3 result = float(sStr2) print(result) # 5.2
阅读更多
相关文章推荐
- 收集常用的Python 内置的各种字符串处理 函数的使用方法
- Python中必须掌握的常用字符串处理函数
- Python常用的字符串处理函数
- python中的字符串常用函数
- Python语言总结 4.2. 和字符串(str,unicode等)处理有关的函数
- 常用的JavaScript字符串处理函数及用法
- 几个常用的Javascript字符串处理函数 spilt(),join(),substring()和indexof()
- 几个常用的JavaScript字符串处理函数 – split()、join()、substring()和indexOf()
- ANSI C 库最常用的几个处理字符串的函数
- 常用的JavaScript字符串处理函数
- [总结] C字符串常用处理函数
- Delphi中常用字符串处理函数
- VC中常用的字符类型及相应的字符串处理函数
- 几个常用函数(切除字符串,时间处理,文件上传)
- SQL常用自定函数 字符串处理
- Python字符串常用函数
- 字符数组的定义、初始化及引用以及一些常用的字符串处理函数
- Python中常用字符串 函数 .
- Delphi中常用字符串处理函数