Python讀書筆記-基礎篇-5.字符串

[導讀]字符串類型也是程序設計中經常用到的類型。字符串的創建時通過單引號''或者雙引號""來創建的。字符串是由數字、字母、下劃線等字符組成的一串字符。

目錄[-]

  1. 字符串類型
  2. 字符串格式化
  3. 字符串內置函數

字符串類型 Top

字符串類型也是程序設計中經常用到的類型。字符串的創建時通過單引號‘’或者雙引號“”來創建的。字符串是由數字、字母、下劃線等字符組成的一串字符。

字符串的操作可以分爲兩種類型,一種是針對字符串內單個字符或者部分字符的操作,一種是針對字符串整體進行的操作。字符串的操作需要用到一些運算符。

  1. +:字符串連接符號。二元操作符,用來將兩個字符串連接到一起形成新的字符串;
  2. *:字符串重複輸出符號。二元操作符,用來將某個字符串重複輸出多次。
  3. []:根據字符在字符串中的索引值或者該字符,字符索引從0開始
  4. [:]:字符串截取符號。語法[start:end];獲取字符串中索引值在range[start,end-1]內的所有字符
  5. in:字符串判斷符號。判斷已知字符串中是否包含給定字符串。
  6. not in:與5)含義想法,用法一致
  7. %:字符串格式化

舉例說明:

			#-*-coding:utf-8-*-
			'''
			Created on 2015年10月20日
			
			@author: Administrator
			'''
			print "定義兩個字符串:"
			str1,str2="hello",'world'
			print str1;
			print str2;
			#+運算符
			ret=str1+str2
			print "兩個字符串的連接:"
			print ret
			#*運算符
			ret=str1*3
			print ret
			print "截取字符串:"
			print ret[2]
			print ret[2:4]
		

字符串格式化Top

Python中對於字符串的操作不僅包括簡單的運算符進行簡單計算還內置了很多字符串函數對字符進行處理。下面我們將一起領略Python內置的字符串函數。不過爲了更美觀看我們字符串的操作結果,我們先領略下Python對字符串的格式化操作

字符串格式化時,Python會使用已經定義的一個字符串模板,模板內包含有格式化符號,這些格式化符號是佔位符,是爲真正的字符預留位置用的。每個格式化符號後可以添加一個類型,用來標識佔位符所代表的數據類型。

			#-*-coding:utf-8-*-
			'''
			Created on 2015年10月20日
			@author:
			Administrator
			'''
			age="I am %d" % (10)
			print age;
		

 其中"I am %d"就是字符串模板,%爲格式化符號,%後面添加了該佔位符所代表的數據類型-整數10。

  1. %s:採用str()格式輸出字符串
  2. %r:採用repr()格式輸出字符串
  3. %c:輸出單個字符
  4. %b:輸出二進制數
  5. %d:輸出十進制數
  6. %o:輸出八進制數
  7. %x:輸出16進制數
  8. 其他一些類型,不再一一贅述。

爲了輸出的美觀化,還經常會用到一些輔助指令:

  1. *:定義數據的顯示寬度
  2. -:左對齊
  3. +:在正數前面添加加號+符號
  4. %:輸出%
  5. m.n:輸出的數據最小位數爲m,如果有浮點數,浮點數的精度爲n

字符串內置函數Top

  1. capitalize():Return a copy of the string S with only its first character capitalized.
    將字符串首字符改寫爲大寫。
  2. center():Return S centered in a string of length width. Padding is done using the specified fill character (default is a space)。
    語法:center(width[,fillchar]);將字符串在width的寬度中居中,並將空閒位置使用fillchar(默認空格)填充。
  3. count():Return the number of non-overlapping occurrences of substring sub in string S[start:end].Optional arguments start and end are interpreted  as in slice notation.
    語法:S.count(sub[, start[, end]]) -> int;查找S[start:end]中sub字符串出現的次數。start默認0,end默認字符串長度。
  4. decode()/encode():字符串根據編碼格式編解碼。
  5. endwith():Return True if S ends with the specified suffix, False otherwise.With optional start, test S beginning at that position.With optional end, stop comparing S at that position.suffix can also be a tuple of strings to try.
    語法:S.endswith(suffix[, start[, end]]) -> bool;判斷S[start:end]是否以suffix結尾。
  6. expandtabs():Return a copy of S where all tab characters are expanded using spaces.If tabsize is not given, a tab size of 8 characters is assumed.
    語法:S.expandtabs([tabsize]) -> string;將tab符號轉換爲tablezie個空格,tablesize默認爲8。
  7. find():Return the lowest index in S where substring sub is found,such that sub is contained within S[start:end].  Optional arguments start and end are interpreted as in slice notation.Return -1 on failure.
    語法:S.find(sub [,start [,end]]) -> int。返回S[start:end]中最早出現子串sub的索引值;如果沒有改子串返回-1。
  8. format():Return a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}').
    語法:S.format(*args, **kwargs) -> string。字符串的格式化函數。字符串中的參數使用{NUM}表示,{0}表示第一個參數,。。。
  9. index():Like S.find() but raise ValueError when the substring is not found.
    語法同find()方法,不同之處在於find()查找不到是返回-1;而index()會拋出異常。
  10. isalnum():Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.
    語法:S.isalnum() -> bool;判斷S中是否全是字母或者數字,如果是返回true;否則返回false。
  11. isalpha():Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise.
    語法語法同isalnum,與isalnum的不同在於isalpha只有當所有字符是字母時才返回true。
  12. isdigit():所有字符是否全是數字。
  13. islower():所有字符是否全是小寫。
  14. isspace():所有字符是否全是空格。
  15. istitle():只有數字符爲大寫,其他字符不出現大寫的情況下,返回true.
  16. isupper():所有字符是否全是大寫。
  17. join():Return a string which is the concatenation of the strings in the iterable.  The separator between elements is S.
    語法:S.join(iterable) -> string;使用S將iterable中每個字符串聯起來。
  18. ljust():Return S left-justified in a string of length width. Padding is done using the specified fill character (default is a space).
    語法:S.ljust(width[, fillchar]) -> string;字符串S在長度width的新串中左對齊,S右側如有空閒位置使用 fillchar填充。
  19. lower():將字符串所有字符轉換爲小寫。
  20. lstrip():裁掉字符串左側的空格或者指定的字符.
  21. replace():字符串替換。
  22. lower():將字符串所有字符轉換爲小寫。
  23. rfind/rindex/rjust/rstrip/resplit():這幾個方法是字符串從右側開始find()/index()/just()/strip()/split(),不再贅述。
  24. rpartition():Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it.  If the separator is not found, return two empty strings and S.
    語法:S.rpartition(sep) -> (head, sep, tail)。如果S.find(sep)!=-1,則返回由字符串sep前面部分,sep本身以及sep後面部分組成的list;否則的話前兩部分都是空字符串。
  25. split():Return a list of the words in the string S, using sep as the delimiter string.  If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
    語法:S.split([sep [,maxsplit]]) -> list of strings。如果S.find(sep)!=-1,則將S使用sep進行分割成包含maxsplit個元素的list;否則返回空。
  26. splitlines(): Return a list of the lines in S, breaking at line boundaries.Line breaks are not included in the resulting list unless keepends is given and true.
    語法:S.splitlines(keepends=False) -> list of strings。按照行進行分割,返回一個包含各行作爲元素的列表;keepends控制結束符是否添加到各行元素中。
  27. strip(): Return a copy of the string S with leading and trailing whitespace removed.If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping。
    語法:S.strip([chars]) -> string or unicode。移除字符串S的頭尾指定字符chars或者空格。
  28. strip(): Return a copy of the string S with leading and trailing whitespace removed.If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping。
    語法:S.strip([chars]) -> string or unicode。移除字符串S的頭尾指定字符chars或者空格。
  29. swapcase():字符串中所有的大小寫互換。
  30. title(): Return a titlecased version of S, i.e. words start with uppercase characters, all remaining cased characters have lowercase.
    語法:將字符串S的每個單詞(以空格分割)的首字母(第一個出現的字母,不包含數字)轉換爲大寫,其他所有字符小寫。
  31. translate():字根據參數table中給定的錶轉換字符串中的字符。
  32. upper():所有字符轉爲大寫。
  33. zfill(): Pad a numeric string S with zeros on the left, to fill a field of the specified width.  The string S is never truncated.
    語法S.zfill(width) -> string;字符串S右對齊,左側的所有空附使用0填充。

舉例說明:

		#-*-coding:utf-8-*-
		'''
		Created on 2015年10月20日
		
		@author: Administrator
		'''
		from string import zfill
		age="i am %d" % (10)
		print "出事字符串:"
		print age;
		print "首字符大寫:"
		print age.capitalize()
		print "字符串居中顯示,空閒字符使用#填充:"
		print age.center(100,"#")
		print "輸出am在字符串中出現的次數:"
		print age.count("am")
		print "字符串是否以某個字符串結尾:"
		print age.endswith("10");
		print "將tab符號轉換爲空格:"
		china="i\tlove\tu"
		value=china.expandtabs(2)
		print value
		print "已知字符串中查找子串:"
		print value.find("love")
		print "字符串的格式化:"
		print ("{0} is {1} years old.".format("Tom", 19))
		print ("{0:_^11} is a boy.".format("Tom"))
		print("My name is {0:10}".format("lreis"))
		print "字符串查找:"
		print value.index("love")
		print "aaaaa111".isalnum()
		print "aaaaa".isalpha();
		print "1111a".isdigit()
		print value.islower();
		print value.isspace();
		print value.istitle();
		print value.isupper();
		print "使用-將test連接"
		print "-".join("test")
		print value.ljust(100,"#")
		print "將字符串全部字符轉換爲小寫:"
		print value.lower();
		print "裁掉字符串左邊的空格或者指定字符"
		print value.lstrip("i");
		print "字符串替換"
		print value.replace("love", "hate")
		print "字符串分區"
		print value.rpartition("lo")
		print "字符串分割"
		print value.split();
		print "行分割"
		print value.splitlines(False)
		print "移除字符串頭尾指定字符或者空格"
		print value.strip("love")
		print "大小寫互換"
		print (value+"LOVE").swapcase();
		print "1i love u".title();
		print "所有字符轉爲大寫:"
		print value.upper();
		print value.zfill(100);
	
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章