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);
	
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值