老男孩python学习自修【第二天】字符串用法

实时处理增量日志最佳实践

主要使用f.seek()和f.tell()实现

字符串处理函数:

s.find(substr, start, end)  查找子字符串,找不到则返回-1,找到则返回对应的索引

s.rfind(substr, start, end)  从右侧开始查找子字符串,找不到则返回-1; 找到则返回对应的索引;返回的结果和find一样,

s.index(substr, start, end)  查找返回子字符串的索引,找不到则报错,报错内容时substring not found

s.rindex(substr, start, end)  从右侧开始查找子字符串,找不到则报错;返回的结果和index一样

s.count(substr, start, end)  统计子字符串出现的次数

s.capitalize()  首字母大写

s.upper()  字符串转大写

s.lower()  字符串转小些

s.swapcase()  字符串大小写互转,大写则转小些,小些则转大写

s.split()  字符串分割变成列表

s.join(list)  使用字符串分割拼接列表

s.startswith(substr)  判断是否以子字符串开头

s.endswith(substr)  判断是否以子字符串结尾

len(str)  字符串的长度

cmp(str1, str2)  比较两个字符串

示例代码如下:

>>> s = "abcdefghijklmn"
>>> s.find("cd")
2
>>> s.rfind("cd")
2
>>> s.find("cd", 4, 9)
-1
>>> s.index("cd")
2
>>> s.index("cd", 4, 9)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s.count("cd")
1
>>> s.count("cd", 4.)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: slice indices must be integers or None or have an __index__ method
>>> s.count("cd", 4, 9)
0
>>> s.capitalise()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'capitalise'
>>> s.capitalize()
'Abcdefghijklmn'
>>> s.upper()
'ABCDEFGHIJKLMN'
>>> s.lower()
'abcdefghijklmn'
>>> s.swapcase()
'ABCDEFGHIJKLMN'
>>> s.split()
['abcdefghijklmn']
>>> s.split("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: empty separator
>>> s.split()
['abcdefghijklmn']
>>>
>>> list = [str(i) for i in range(9)]
>>> list
[']
>>> "==".join(list)
'0==1==2==3==4==5==6==7==8'
上一篇:使用exe4j工具制作简单的java应用程序


下一篇:spyder 安装