1. 程式人生 > >(自興人工智能)全面了解 "字符串" str

(自興人工智能)全面了解 "字符串" str

第一個 log word false post str 轉義字符 字符串分割 clas

#字符串的聲明可以單引號雙引號三引號,單引號和雙引號沒什麽區別,單三引裏的字符可以原樣保存 
a = ‘adf‘
a = " "
a = ‘‘‘\n\t‘‘‘
#字符串可以用r語來轉義字符串裏面的內容都會原樣輸出 
a =r‘\t\n\a‘
print a
\t\n\a
#字符串也是一個序列可以索引查找 切片 拼接 單不支持原位改變
#查找
a = ‘a12b‘ 
a[1]
Out[10]: ‘1‘
#切片
a[0:2]
Out[11]: ‘a1‘
#拼接
a = ‘abc‘
b = ‘123‘
a+b
Out[38]: ‘abc123‘
#字符串的一些方法 
a = ‘asdfADDFaad‘
a.lower() #lower() 方法是把字符串裏的所有大寫字母變成小寫 並返回一個新的字符串
Out[9]: ‘asdfaddfaad‘

a = ‘aadfAAadfA‘
a = a.upper() #upper() 方法是把字符串裏的所有小寫字母變成大寫 並返回一個新的字符串
print a
AADFAAADFA

a = ‘abc‘
a = a.capitalize() #capitalize() 方法是把字符串開頭第一個字母變成大寫 並返回一個新的字符串
print a
Abc

a = ‘ab cd dd‘
a = a.title() #title() 方法是把字符串裏的每一個單詞的第一個字母變成大寫 並返回一個新的字符串
print a
Ab Cd Dd
a = ‘avc‘
bl = a.startswith(‘a‘) #startswith() 方法是判斷是否以傳入的參數開頭
print bl
True

a = ‘avc‘
bl = a.endswith(‘v‘) #endswith() 方法是判斷是否以傳入的參數結尾
print bl
False

a = ‘abc123‘
a.find(‘2‘) #find() 方法是查找字符串中有沒有傳入的參數 沒有返回-1 有返回第一個的下表
Out[25]: 4
a.find(‘d‘)
Out[26]: -1

a = ‘a,b,c‘
a.split(‘,‘) #split() 方法是以傳入的參數把字符串分割開並返回一個列表
Out[30]: [‘a‘, ‘b‘, ‘c‘]
a = ‘a b c‘
a.split() #沒有傳參默認為空格
Out[32]: [‘a‘, ‘b‘, ‘c‘]

a = ‘a,b,c‘
a.split(‘,‘,1) #也可以指定分割的次數 最多分割這麽多次
Out[34]: [‘a‘, ‘b,c‘]

ls = [‘a‘,‘b‘,‘c‘]
‘+‘.join(ls) #join()方法是以什麽把一個序列拼接起來,傳參要傳序列
Out[35]: ‘a+b+c‘

name = ‘angrd‘
name.center(20) #center() 方法是準備20字符name不夠默認用空格填充並把name放中間
Out[45]: ‘ angrd ‘
name.center(20,‘-‘)#也可以用其他東西填充
Out[46]: ‘-------angrd--------‘

#字符串的編碼
a = ‘a‘
ord(a) #ord() 方法是返回‘a‘在代碼庫中的編碼
Out[48]: 97



#字符串的格式化
score = 100
name = ‘angrd‘
word = ‘{}打了{}‘.format(name,score) #中括號為占位符.format()方法把字符串填進去
print word
angrd打了100

score = 100
name = ‘angrd‘
word = ‘%s打了%s‘%(name,score) #%s一樣也是占位符
print word
angrd打了100

(自興人工智能)全面了解 "字符串" str