个人觉得字符串实在是个比较灵活的数据格式,对其可做的操作也很多,也看了很多资料,感觉还是需要用到的时候去查查文档,该用什么方法好。以下是整理的一些资料,方便日后查阅。
Python Strings
Python有一个名为“str”的内置字符串类,它有许多方便的功能(有一个名为“string”的旧模块,最好不用)。 尽管单引号更常用,但字符串文字可以用双引号或单引号括起来。
反斜杠转义在单引号和双引号文字中以通常的方式工作 - 例如 \n、’、\“。双引号字符串文字可以包含单引号而不用任何大惊小怪(例如“我没有这样做”)同样单引号字符串可以包含双引号。字符串文字可以跨越多行,但那里 必须是每行末尾的反斜杠\才能转义换行符。三重引号中的字符串文字"""或’’'可以跨越多行文本。
Python字符串是“不可变的”,这意味着它们在创建后无法更改(Java字符串也使用这种不可变的样式)。 由于字符串不能更改,表示字符串计算值就是构造新字符串。 因此,例如表达式(‘hello’+‘there’)接受2个字符串’hello’和’there’并构建一个新字符串’hellothere’。
String Methods
以下是一些最常见的字符串方法。 方法就像一个函数,但它在一个对象上“运行”。 如果变量s是一个字符串,那么代码s.lower()在该字符串对象上运行lower()方法并返回结果(这个在对象上运行的方法的想法是构成Object的基本思想之一——面向对象编程,OOP)。 以下是一些最常见的字符串方法:
- s.lower(), s.upper() – returns the lowercase or uppercase version of the string
- s.strip() – returns a string with whitespace removed from the start and end
- s.isalpha()/s.isdigit()/s.isspace()… – tests if all the string chars are in the various character classes
- s.startswith(‘other’), s.endswith(‘other’) – tests if the string starts or ends with the given other string
- s.find(‘other’) – searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
- s.replace(‘old’, ‘new’) – returns a string where all occurrences of ‘old’ have been replaced by ‘new’
- s.split(‘delim’) – returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it’s just text. ‘aaa,bbb,ccc’.split(’,’) -> [‘aaa’, ‘bbb’, ‘ccc’]. As a convenient special case s.split() (with no arguments) splits on all whitespace chars.
- s.join(list) – opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. ‘—’.join([‘aaa’, ‘bbb’, ‘ccc’]) -> aaa—bbb—ccc
String Slices
“切片”语法是引用序列子部分的一种方便方法 - 通常是字符串和列表。
切片s [start:end]是从开始处开始并向上延伸但不包括结束的元素。
String %
Python有一个类似printf() 的工具来组合一个字符串。%运算符在左侧获取printf类型的格式字符串(%d int,%s字符串,%f /%g浮点数),匹配值在右侧的元组中(元组由逗号分隔的值组成,通常在括号内分组):
# % operator
text = "%d little pigs come out, or I'll %s, and I'll %s, and I'll blow your %s down." % (3, 'huff', 'puff', 'house')
More operations
keep updating…
References
- http://www.runoob.com/python3/python3-string.html
- https://www.jb51.net/article/151093.htm