字符串處理與特殊函數(shù)
用引號括起來的字符集合稱之為字符串,引號可以使一對單引號、雙引號片迅、三引號(單/雙)磅叛。
創(chuàng)建字符串很簡單:
var1 = 'hello world!'
var2 = "python"
var3 = '''hello world'''
var4 = """python"""
如果需要輸出 hello "dear"
怎么辦屑咳?
print ("hello \"dear\" ")
print ('''hello "dear" ''')
同時'''
支持內(nèi)容換行
python 訪問字符串中的值
python不支持單字符類型,單字符在python也是作為一個字符串處理的弊琴。
python訪問子字符串兆龙,可以使用方括號來截取字符串:
var1 = 'hello world'
var2 = "python programming"
print ("var1[0]:",var1[0])
print ("var2[1:5]:",var2[1:5])
以上實例執(zhí)行結(jié)果為:
var1[0]: h
var2[1:5]: ytho
python字符串更新
本質(zhì)是另外開辟空間創(chuàng)建了一個新的字符串
var1='hello world'
print("updated mystr:",var1[:6] + 'python')
以上實例執(zhí)行結(jié)果為:
updated mystr: hello python
python字符串運算符
以下實例部分a
為字符串'hello'
,b
為字符串'python'
操作符 | 描述 | 實例 |
---|---|---|
+ | 字符串連接 |
a+b 輸出為:hellopython
|
* | 重復輸出字符串 |
a*2 輸出為:hellohello
|
[] | 通過索引獲取字符 |
a[1] 輸出結(jié)果為:e
|
[:] | 截取字符串中的一部分 |
a[1:4] 輸出結(jié)果為:ell
|
in | 成員運算符 | 如果字符串中包含給定的字符返回true
|
not in | 成員運算符 | 如果字符串中不包含給定的字符返回 true
|
r/R | 原始字符串 | 字符串直接按照字面的意思來使用敲董,沒有轉(zhuǎn)義或不能打印的字符 |
原始字符串在字符串的第一個引號前加上字母“r”(可以大小寫)以外紫皇,與普通字符串有著幾乎完全相同的語法慰安。
python字符串格式化
在python
中,字符串格式化使用與C中sprintf
函數(shù)一樣的語法聪铺。
print("my name is %s and weight is %d kg" % ("john",2) )
以上實例執(zhí)行結(jié)果為:
my name is john and weight is 2 kg
字符串中各種函數(shù)
find(str,start,end)函數(shù) 查找字符串化焕;start 和 end可以省略,找不到時返回 -1
mystr="hello world"
mystr.find('hello',0,len(mystr))`
index(str,start,end)函數(shù) 定位索引铃剔;start 和 end可以省略撒桨,找不到時拋異常
count(str,start,end)函數(shù) 返回str在start和end之間 在mystr里面出現(xiàn)的次數(shù)
decode(encoding,errors) 以encoding指定的編碼格式解碼mystr
mystr.decode(encoding='UTF-8',errors='strict')
encode(encoding,errors) 以encoding指定的編碼格式編碼mystr
mystr.decode(encoding='UTF-8',errors='strict')
replace(str1,str2,count) 把mystr中的str1替換成str2,如果count指定,則替換不超過count次
mystr.replace(str,str2,mystr.count(str1))
**split(str,maxsplit) ** 以str為分隔符切片键兜,如果maxsplit有指定值凤类,則僅分割maxsplit個子字符串
capitalize() 把字符串的第一個字符大寫
可以使用mystr. 然后回車 查看該字符串的處理方法有哪些
可以使用 help(方法名)查看方法的使用方式