一、字符串的连接和复制
字符串间的连接用“+”号,不同数据类型之间不能直接连接。
>>>'Yvette' + 'zheng'
'Yvettezheng'
>>>'Yvette' + 1
Traceback (most recent call last):
File "<ipython-input-2-c795e6c59527>", line 1, in <module>
'Yvette' + 1
TypeError: must be str, not int
二、字符串切片
字符串切片string[0:2]可以任意选取内容,也可以指定位置进行替换。
>>>'Hello World'[6:]
'World'
>>>'Hello World'[:6] + 'Yvette'
'Hello Yvette'
三、原始字符串类型
字符串前面添加r,表示字符串按字面来,避免转义。
>>>print('Hello\nWorld')
Hello
World
>>>print(r'Hello\nWorld')
Hello\nWorld
四、内建函数
1、格式化字符串string.format()
例子 {0:^10}\t{1:{3}^10}\t{2:^10}.format("排名","学校名称","总分", chr(12288))
参考连接:http://www.runoob.com/python/att-string-format.html
https://docs.python.org/3/library/string.html#grammar-token-conversion
2、_repr_和_str_的区别
3、删除首尾字符
>>>spam = ' Hello World '
>>>spam.strip()
'Hello World'
>>>spam.lstrip()
'Hello World '
>>>spam.rstrip()
' Hello World'
>>>spam = 'SpamapmSBaconSpamEggspamSpam'
>>>spam.strip('ampS') #a、m、p、S的顺序不重要
'BaconSpamEggs'
4、分割sep.split()和连接sep.join()
>>>'.'.join(['My','name','is','Yvette'])
'My.name.is.Yvette'
>>>'My name is Yvette'.split()
['My', 'name', 'is', 'Yvette']
5、文本对齐
>>>'Hello'.rjust(10)
' Hello'
>>>'Hello'.ljust(10)
'Hello '
>>>'Hello'.center(20,'=')
'=======Hello========'
打印表格式数据
def printPicnic(itemsDict,leftWidth,rightWidth):
print('PICNIC ITEMS'.center(leftWidth+rightWidth, '-'))
for k, v in itemsDict.items():
print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 20, 6)
-------PICNIC ITEMS-------
sandwiches.......... 4
apples.............. 12
cups................ 4
cookies............. 8000
6、大小写转换
>>>spam = 'Hello World!'
>>>spam.upper() #全部变为大写
'HELLO WORLD!'
>>>spam.lower() #全部变为小写
'hello world!'
7.布尔值判断.isX方法
.isupper()返回True,如果字符串至少有一个字母,并且所有字母都是大写;
.islower()返回True,如果字符串至少有一个字母,并且所有字母都是小写;
.isalpha()返回True,如果字符串只包含字母,并且非空;
.isalnum()返回True,如果字符串只包含字母和数字,并且非空;
.isdecimal()返回True,如果字符串只包含数字,并且非空;
.isspace()返回True,如果字符串只包含空格、制表符和换行,并且非空;
.istitle()返回True,如果字符串仅包含以大写字母开头、后面都是小写字母的单词。