1.去除空格
str.strip():刪除字串兩邊的指定字元,括號的寫入指定字元,預設為空格
>>> a=' hello '>>> b=a.strip()
>>> print(b)
hello
str.lstrip():刪除字串左邊的指定字元,括號的寫入指定字元,預設為空格
str.rstrip():刪除字串右邊指定字元,預設為空格
2.複製字串
>>> a='hello world'>>> b=a
>>> print(a,b)
hello world hello world
3.連線字串
+:連線2個字串#str.index 和str.find 功能相同,區別在於find()查詢失敗會返回-1,不會影響程式執行。一般用find!=-1或者find>-1來作為判斷條件。>>> a='hello '
>>> b='world'
>>> print(a+b)
hello world
str.join:連線2個字串,可指定連線符號(關於join,讀者可以自己去檢視一些相關資料)
>>> a='hello '
>>> b='####'
>>> a.join(b)
'#hello #hello #hello #'
str.index:檢測字串中是否包含子字串str,可指定範圍
a='hello world'
>>> a.index('l')
2>>> a.index('x')
traceback (most recent call last):
file "", line 1, in
a.index('x')
valueerror: substring not found
str.find:檢測字串中是否包含子字串str,可指定範圍
>>> a='hello world'
>>> a.find('l')
2>>> a.find('x')
-15.比較字串
1 >>> a=1002 >>> b=80
3 >>> cmp(a,b)
4 16.是否包含指定字串
1 in |not in2 >>> a='hello world'
3 >>> 'hello' in a
4 true
5 >>> '123' not in a
6 true
7.字串長度
1 str.lens.lower() #轉換為小寫2 >>> a='hello world'
3 >>> print(len(a))
4 11
8.字串中字母大小寫轉換
>>> a='hello world'
>>> print(a.lower())
hello world
s.upper() #轉換為大寫
>>> a='hello world'
>>> print(a.upper())
hello world
s.swapcase() #大小寫互換
>>> a='hello world'
>>> print(a.swapcase())
hello world
s.capitalize() #首字母大寫
>>> a='hello world'
>>> print(a.capitalize())
hello world
9.將字串放入中心位置可指定長度以及位置兩邊字元
1 str.center()2 >>> a='hello world'
3 >>> print(a.center(40,'*'))
4 **************hello world***************
10.字串統計
>>> a='hello world's.startswith(prefix[,start[,end]]) #是否以prefix開頭>>> print(a.count('l'))
311.字串的測試、判斷函式,這一類函式在string模組中沒有,這些函式返回的都是bool值
s.endswith(suffix[,start[,end]]) #以suffix結尾
s.isalnum() #是否全是字母和數字,並至少有乙個字元
s.isalpha() #是否全是字母,並至少有乙個字元
s.isdigit() #是否全是數字,並至少有乙個字元
s.isspace() #是否全是空白字元,並至少有乙個字元
s.islower() #s中的字母是否全是小寫
s.isupper() #s中的字母是否便是大寫
s.istitle() #s是否是首字母大寫的
12.字串切片
str = '0123456789′
print str[0:3] #擷取第一位到第三位的字元
print str[:] #擷取字串的全部字元
print str[6:] #擷取第七個字元到結尾
print str[:-3] #擷取從頭開始到倒數第三個字元之前
print str[2] #擷取第三個字元
print str[-1] #擷取倒數第乙個字元
print str[::-1] #創造乙個與原字串順序相反的字串
print str[-3:-1] #擷取倒數第三位與倒數第一位之前的字元
print str[-3:] #擷取倒數第三位到結尾
print str[:-5:-3] #逆序擷取,擷取倒數第五位數與倒數第三位數之間
C 字串系列1 字元編碼基礎
一 從ascii碼到unicode 計算機發明後,為了在計算機中表示字元,人們制定了一種編碼,叫ascii碼。ascii碼由乙個位元組中的7位 bit 表示,範圍是0x00 0x7f 共128個字元。他們以為這128個數字就足夠表示abcd.abcd.1234 這些字元了。咳.說英語的人就是 笨 後...
程式語言系列 1 字串 (C C )
c 語言中,字串實際上是使用 0 字元終止的一維字元陣列 include 1.建立 char greeting 6 char greeting hello 2.獲取字串長度 len strlen str1 3.複製 strcpy str1,str2 把str2複製到str1 4.連線 strcat ...
python學習1 字串變數
字串是任意長度的字元集合。當向python中處理乙個字串時,必須有一對引號把字串括起來。而這個引號可以是單引號,也可以是雙引號,還可以是三層引號。這三種引號在python中是等價的。1.之所以有三種引號的存在,是為了輸出字串中包含的引號 單引號或者雙引號 而三層引號多用於換行輸出。這樣有了三種引號的...