平時敲**的時候字串處理規範,方法和一些小技巧總會記不住,需要現查,這裡mark小結一下
在python中,單引號和雙引號在表示字串沒有區別
str1="python is 'beautiful'"
str2='python is "beautiful"'
print str1
print str2
這樣做的優點從上面**可以看出,單引號定義字串,裡面雙引號被認定是普通字元,雙引號定義字串也一樣,都不需要進行轉義,這就是python開發者常說的易用性。
1、%格式化:%[(name)][flags][width].[precision]typecode
width:可選,字串所佔總寬度
.precision:可選,小數點精度
typecode:必選,s,d,f 等等
**示例如下:
#version是指定key值,如果不指定,按照順序對應
str1="python%(version)d is '%(how)s'"%
#%s %.2f %d,float精確度,整數
str2='python%.1f is "beautiful"'%(2.7)
#d前面的4表示寬度,0表示flags值
str3='heihei%04d'%-3.1212121
#7代表字串總的所佔寬度
str4='xixi%+7.2f'%-2.213
print str1
print str2
print str3
print str4
python3 is 'beautiful'
python2.7 is "beautiful"
heihei-003
xixi +2.21
2、format格式化:採用{}和:來取代%,[[fill]align][sign][#][0][width][,][.precision][type]
sign:可選,有無符號數字
#:可選,對於二進位制、八進位制、十六進製制,如果加上#,會顯示 0b/0o/0x,否則不顯示
,:可選,數字分隔符,eg:1,000,000
width:可選,所佔寬度
.precision:可選,小數字保留精度
type:可選,格式化型別 s,f,d
示例**如下:
args=['python','2.7']
kw=#format基本形式
s1="{}{} is beautiful".format('python','2.7')
#位置引數
s2="{}{} is beautiful".format(*args)
#關鍵字引數
s3=" is beautiful".format(**kw)
#+表示填充的內容 ^表示內容居中,11表示所佔位數,.2f表示精度與進製
s4="heihei ".format(10.345)
print s1
print s2
print s3
print s4
python2.7 is beautiful
python2.7 is beautiful
python2.7 is beautiful
heihei +++10.35+++
1、大小寫轉換
示例**如下:
str='abc,xyz'
print str.lower()
print str.upper()
print str.title()
print str.capitalize()
print str.swapcase()
abc,xyz
abc,xyz
abc,xyz
abc,xyz
abc,xyz
2、更新和替換
str.replace(old,new,count):將old字串替換為new的字串,count表示前count個被替換
str="python2.7 is beautiful 2.7"
#1代表,只有前1個被替換
s=str.replace('2.7', '3',1)
print s
注:簡單的可以用replace,但是python大部分複雜的字串替換,會採用正規表示式去匹配和替換。
3、分割和連線
示例**如下:
str=" python2.7 is beautiful "
#以t分割,分割一次
s1=str.split('t',1)
#以t分割,再以!連線
s2="!".join(str.split('t'))
#去掉開頭結尾空格,再以空格連線
s3=" ".join(str.strip())
#以空格分割,再以空格連線,從下面的字串長度可以看出作用相當於strip()函式,
s4=" ".join(str.split())
print s1
print s2
print s3
print s4
print len(str),len(s4)
[' py', 'hon2.7 is beautiful ']
py!hon2.7 is beau!iful
p y t h o n 2 . 7 i s b e a u t i f u l
python2.7 is beautiful
26 22
4、刪除字元
有效利用分割,拼接等方法;或者採用strip('a')刪除兩端的字元
5、遍歷
enumerate():用於將可遍歷的資料物件(列表、元組或字串)組合為乙個索引序列,同時列出資料和資料下標,一般用於for迴圈。
#可以同時輸出下標和內容
s="python"
for i,j in enumerate(s):
print i,j
seq=["sadf","sdafsdfasdfa","gjgjghj"]
for m,n in enumerate(seq):
print m,n
#遍歷s="python"
for i in iter(s):
print i
python字串小結
字串 str 作用 用來記錄文字資訊 字串表示方法 在非注釋中凡是用引號括起來的部分是字串 單引號 雙引號 三單引號 三雙引號 空字串字面值的表示方法 空字串的布林值測試值bool x 為false 非空字串字面值的表示方法 hello 單引號和雙引號的區別 單引號內可以包含雙引號 雙引號不算結束符...
python 字串使用 小結
字串在語言中的使用應該是很廣泛的了吧。使用語言不可能不學習字串,但是字串除了常用的方法還有其他許多的方法,這裡做個小結。一 建立字串 s s a,b test1 test2 二 字串數學操作 加 a,b test1 test2 a b test1test2 乘 a 2 test1test1 test...
字串小結
1.字串概念 字串是位於雙引號中的字串行 在記憶體中以 0 結束,所佔位元組比實際多乙個 2.字串的初始化 在c語言中沒有專門的字串變數,通常用乙個字元陣列來存放乙個字串。前面介紹字串常量時,已說明字串總是以 0 作為串的結束符。因此當把乙個字串存入乙個陣列時,也把結束符 0 存入陣列,並以此作為該...