1、* 重复输出字符串
>>> print('hello'*10) hellohellohellohellohellohellohellohellohellohello
2、[], [:] 通过索引获取字符串中的字符,这里和列表中的切片方法一样
>>> print('hello word'[2:]) llo word
3、in 成员运算符,如果字符串中包含给定的字符,则返回True
>>> print('ell' in 'hello word') True
4、% 格式化字符串
>>> print('alex is a good teacher') alex is a good teacher >>> print('%s is a good teacher'%'alex') alex is a good teacher
5、+ ,‘’.join 字符串拼接(两种方法)
>>> a = 'abc' >>> b = '123' >>> c = a + b >>> print(c) abc123
>>> a = 'abc' >>> b = '123' >>> c = ''.join([a,b]) >>> print(c) abc123
字符串的内置方法:
st = ‘hello kitty’
1、count #统计字符串中的元素个数 |||||
>>> st = 'hello kitty' >>> print(st.count('l')) 2
2、capitalize #将整个字符串中的首个字母大写
>>> print(st.capitalize()) Hello kitty
3、center # 居中 |||||
>>> print(st.center(50,'-')) -------------------hello kitty--------------------
4、endswith # 以某个内容结尾,返回布尔值
>>> print(st.endswith('y')) True
5、startswith # 以某个内容开头,返回布尔值 |||||
>>> print(st.startswith('h')) True
6、expandtabs(tabsize=20)
>>> st = 'he\tllo kitty' >>> print(st.expandtabs(tabsize=20)) he llo kitty
7、find #查找第一个元素,并返回索引值 |||||
>>> st = 'hello kitty' >>> print(st.find('t')) 8
8、format format_map #格式化输出 ||||||
>>> st = 'hello kitty {name} is {age}' >>> print(st.format(name = 'alex',age = 37)) hello kitty alex is 37
>>> st = 'hello kitty {name} is {age}'
>>> print(st.format_map({'name':'alex','age':37}))
hello kitty alex is 37
9、index #查找元素并返回索引值,元素不存在则会报错 ||||||
>>> print(st.index('a')) 14 >>> print(st.index('w')) Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> print(st.index('w')) ValueError: substring not found
10、 isalnum # 判断字符串中是否包含字母或数字,返回布尔值
>>>print('abc456'.isalnum())
True
11、isdigit isnumeric # 判断字符串是否是一个整型,返回布尔值
>>> print('123456'.isdigit()) True
>>> print('123456'.isnumeric())
True
12、isidentifier # 判断是否是非法字符
>>> print('123456'.isidentifier()) False
13、islower # 判断所有字符串是否是小写
>>> print('asda'.islower()) True
14、isupper # 判断所有字符串是否是大写
>>> print('ASD'.isupper()) True
15、isspace # 判断字符串中是否是空格
>>> print(' '.isspace()) True
16、istitle # 判断是否是标题(标题的单词首字母是大写)
>>> print('My Title'.istitle()) True
17、lower #所有大写变小写 |||||
>>> print('My Title'.lower()) my title
18、upper #所有小写变大写 |||||
>>> print('My Title'.upper()) MY TITLE
19、swapcase #字母大小写翻转
>>> print('My Title'.swapcase()) mY tITLE
20、ljust #左对齐 rjust #右对齐
>>> print('My Title'.ljust(50,'*')) My Title******************************************
>>> print('My Title'.rjust(50,'*'))
******************************************My Title
21、strip #去掉空格和换行符 |||||
print(' My Title\n') print('ok') My Title ok print(' My Title\n'.strip()) print('ok') My Title ok
22、replace #替换 |||||
>>> print('My title'.replace('t','lesson',2)) #参数2,表示替换几次 My lessonilessonle
23、split #分割 |||||
>>> print('My title'.split('i'))
['My t', 'tle']
22、title # 以标题的形式输出
>>> print('My title title'.title()) My Title Title