字符串的定義與創建
字符串是一個有序的字符的集合,用於存儲和表示基本的文本信息,' '或'' ''或''' '''中間包含的內容稱之爲字符串
創建:
s = 'Hello,Eva!How are you?'
字符串的特性與常用操作
特性:
1.按照從左到右的順序定義字符集合,下標從0開始順序訪問,有序
補充:
1.字符串的單引號和雙引號都無法取消特殊字符的含義,如果想讓引號內所有字符均取消特殊意義,在引號前面加r,如name=r'l\thf'
2.unicode字符串與r連用必需在r前面,如name=ur'l\thf'
常用操作:
#索引 s = 'hello' >>> s[1] 'e' >>> s[-1] 'o' >>> s.index('e') 1 #查找 >>> s.find('e') 1 >>> s.find('i') -1 #移除空白 s = ' hello,world! ' s.strip() s.lstrip() s.rstrip() s2 = '***hello,world!***' s2.strip('*') #長度 >>> s = 'hello,world' >>> len(s) 11 #替換 >>> s = 'hello world' >>> s.replace('h','H') 'Hello world' >>> s2 = 'hi,how are you?' >>> s2.replace('h','H') 'Hi,How are you?' #切片 >>> s = 'abcdefghigklmn' >>> s[0:7] 'abcdefg' >>> s[7:14] 'higklmn' >>> s[:7] 'abcdefg' >>> s[7:] 'higklmn' >>> s[:] 'abcdefghigklmn' >>> s[0:7:2] 'aceg' >>> s[7:14:3] 'hkn' >>> s[::2] 'acegikm' >>> s[::-1] 'nmlkgihgfedcba'