python字符串操作和string模块代码分析 牛人总结 转存

原文链接: http://blog.chinaunix.net/uid-25992400-id-3283846.html

任何语言都离不开字符,那就会涉及对字符的操作,尤其是脚本语言更是频繁,不管是生产环境还是面试考验都要面对字符串的操作。

python的字符串操作通过2部分的方法函数基本上就可以解决所有的字符串操作需求:

  • python的字符串属性函数
  • python的string模块

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  1. 字符串属性函数

系统版本:CentOS release 6.2 (Final)2.6.32-220.el6.x86_64

python版本:Python 2.6.6

字符串属性方法

  1. >>> str=‘string learn‘
  2. >>> dir(str)
  3. [‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__getslice__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘_formatter_field_name_split‘, ‘_formatter_parser‘, ‘capitalize‘, ‘center‘, ‘count‘, ‘decode‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘, ‘index‘, ‘isalnum‘, ‘isalpha‘, ‘isdigit‘, ‘islower‘, ‘isspace‘, ‘istitle‘, ‘isupper‘, ‘join‘, ‘ljust‘, ‘lower‘,‘lstrip‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘,‘split‘, ‘splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]

可以将这些方法按功能用途划分为以下几种类型:

字符串格式输出对齐

  1. >>> str=‘stRINg lEArn‘
  2. >>>
  3. >>> str.center(20)      #生成20个字符长度,str排中间
  4. ‘    stRINg lEArn    ‘
  5. >>>
  6. >>> str.ljust(20)       #str左对齐
  7. ‘stRINg lEArn        ‘
  8. >>>
  9. >>> str.rjust(20)       #str右对齐
  10. ‘        stRINg lEArn‘
  11. >>>
  12. >>> str.zfill(20)       #str右对齐,左边填充0
  13. ‘00000000stRINg lEArn‘

大小写转换

  1. >>> str=‘stRINg lEArn‘
  2. >>>
  3. >>> str.upper() #转大写
  4. ‘STRING LEARN‘
  5. >>>
  6. >>> str.lower() #转小写
  7. ‘string learn‘
  8. >>>
  9. >>> str.capitalize() #字符串首为大写,其余小写
  10. ‘String learn‘
  11. >>>
  12. >>> str.swapcase() #大小写对换
  13. ‘STrinG LeaRN‘
  14. >>>
  15. >>> str.title() #以分隔符为标记,首字符为大写,其余为小写
  16. ‘String Learn‘

字符串条件判断

  1. >>> str=‘0123‘
  2. >>> str.isalnum()  #是否全是字母和数字,并至少有一个字符
  3. True
  4. >>> str.isdigit()   #是否全是数字,并至少有一个字符
  5. True
  6. >>> str=‘abcd‘
  7. >>> str.isalnum()
  8. True
  9. >>> str.isalpha()   #是否全是字母,并至少有一个字符
  10. True
  11. >>> str.islower()   #是否全是小写,当全是小写和数字一起时候,也判断为True
  12. True
  13. >>> str=‘abcd0123‘
  14. >>> str.islower()   #同上
  15. True
  16. >>> str.isalnum()
  17. True
  18. >>> str=‘ ‘
  19. >>> str.isspace()    #是否全是空白字符,并至少有一个字符
  20. True
  21. >>> str=‘ABC‘
  22. >>> str.isupper()    #是否全是大写,当全是大写和数字一起时候,也判断为True
  23. True
  24. >>> str=‘Abb Acc‘
  25. >>> str.istitle()    #所有单词字首都是大写,标题
  26. True
  27. >>> str=‘string learn‘
  28. >>> str.startswith(‘str‘) #判断字符串以‘str‘开头
  29. True
  30. >>> str.endswith(‘arn‘)   #判读字符串以‘arn‘结尾
  31. True

字符串搜索定位与替换

  1. >>> str=‘string lEARn‘
  2. >>>
  3. >>> str.find(‘a‘)      #查找字符串,没有则返回-1,有则返回查到到第一个匹配的索引
  4. -1
  5. >>> str.find(‘n‘)
  6. 4
  7. >>> str.rfind(‘n‘)     #同上,只是返回的索引是最后一次匹配的
  8. 11
  9. >>>
  10. >>> str.index(‘a‘)     #如果没有匹配则报错
  11. Traceback (most recent call last):
  12. File "", line 1, in <module>
  13. ValueError: substring not found
  14. >>> str.index(‘n‘)     #同find类似,返回第一次匹配的索引值
  15. 4
  16. >>> str.rindex(‘n‘)    #返回最后一次匹配的索引值
  17. 11
  18. >>>
  19. >>> str.count(‘a‘)     #字符串中匹配的次数
  20. 0
  21. >>> str.count(‘n‘)     #同上
  22. 2
  23. >>>
  24. >>> str.replace(‘EAR‘,‘ear‘)  #匹配替换
  25. ‘string learn‘
  26. >>> str.replace(‘n‘,‘N‘)
  27. ‘striNg lEARN‘
  28. >>> str.replace(‘n‘,‘N‘,1)
  29. ‘striNg lEARn‘
  30. >>>
  31. >>>
  32. >>> str.strip(‘n‘)   #删除字符串首尾匹配的字符,通常用于默认删除回车符
  33. ‘string lEAR‘
  34. >>> str.lstrip(‘n‘)  #左匹配
  35. ‘string lEARn‘
  36. >>> str.rstrip(‘n‘)  #右匹配
  37. ‘string lEAR‘
  38. >>>
  39. >>> str=‘ tab‘
  40. >>> str.expandtabs()  #把制表符转为空格
  41. ‘      tab‘
  42. >>> str.expandtabs(2) #指定空格数
  43. ‘ tab‘

字符串编码与解码

  1. >>> str=‘字符串学习‘
  2. >>> str
  3. ‘\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2\xe5\xad\xa6\xe4\xb9\xa0‘
  4. >>>
  5. >>> str.decode(‘utf-8‘)               #解码过程,将utf-8解码为unicode
  6. u‘\u5b57\u7b26\u4e32\u5b66\u4e60‘
  7. >>> str.decode(‘utf-8‘).encode(‘gbk‘)  #编码过程,将unicode编码为gbk
  8. ‘\xd7\xd6\xb7\xfb\xb4\xae\xd1\xa7\xcf\xb0‘
  9. >>> str.decode(‘utf-8‘).encode(‘utf-8‘)  #将unicode编码为utf-8
  10. ‘\xe5\xad\x97\xe7\xac\xa6\xe4\xb8\xb2\xe5\xad\xa6\xe4\xb9\xa0‘

字符串分割变换

  1. >>> str=‘Learn string‘
  2. >>> ‘-‘.join(str)
  3. ‘L-e-a-r-n- -s-t-r-i-n-g‘
  4. >>> l1=[‘Learn‘,‘string‘]
  5. >>> ‘-‘.join(l1)
  6. ‘Learn-string‘
  7. >>>
  8. >>> str.split(‘n‘)
  9. [‘Lear‘, ‘ stri‘, ‘g‘]
  10. >>> str.split(‘n‘,1)
  11. [‘Lear‘, ‘ string‘]
  12. >>> str.rsplit(‘n‘,1)
  13. [‘Learn stri‘, ‘g‘]
  14. >>>
  15. >>> str.splitlines()
  16. [‘Learn string‘]
  17. >>>
  18. >>> str.partition(‘n‘)
  19. (‘Lear‘, ‘n‘, ‘ string‘)
  20. >>> str.rpartition(‘n‘)
  21. (‘Learn stri‘, ‘n‘, ‘g‘)

string模块源代码

  1. """A collection of string operations (most are no longer used).
  2. Warning: most of the code you see here isn‘t normally used nowadays.
  3. Beginning with Python 1.6, many of these functions are implemented as
  4. methods on the standard string object. They used to be implemented by
  5. a built-in module called strop, but strop is now obsolete itself.
  6. Public module variables:
  7. whitespace -- a string containing all characters considered whitespace
  8. lowercase -- a string containing all characters considered lowercase letters
  9. uppercase -- a string containing all characters considered uppercase letters
  10. letters -- a string containing all characters considered letters
  11. digits -- a string containing all characters considered decimal digits
  12. hexdigits -- a string containing all characters considered hexadecimal digits
  13. octdigits -- a string containing all characters considered octal digits
  14. punctuation -- a string containing all characters considered punctuation
  15. printable -- a string containing all characters considered printable
  16. """
  17. # Some strings for ctype-style character classification
  18. whitespace = ‘ \t\n\r\v\f‘
  19. lowercase = ‘abcdefghijklmnopqrstuvwxyz‘
  20. uppercase = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ‘
  21. letters = lowercase + uppercase
  22. ascii_lowercase = lowercase
  23. ascii_uppercase = uppercase
  24. ascii_letters = ascii_lowercase + ascii_uppercase
  25. digits = ‘0123456789‘
  26. hexdigits = digits + ‘abcdef‘ + ‘ABCDEF‘
  27. octdigits = ‘01234567‘
  28. punctuation = """!"#$%&‘()*+,-./:;<=>[email protected][\]^_`{|}~"""
  29. printable = digits + letters + punctuation + whitespace
  30. # Case conversion helpers
  31. # Use str to convert Unicode literal in case of -U
  32. l = map(chr, xrange(256))
  33. _idmap = str(‘‘).join(l)
  34. del l
  35. # Functions which aren‘t available as string methods.
  36. # Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
  37. def capwords(s, sep=None):
  38. """capwords(s [,sep]) -> string
  39. Split the argument into words using split, capitalize each
  40. word using capitalize, and join the capitalized words using
  41. join. If the optional second argument sep is absent or None,
  42. runs of whitespace characters are replaced by a single space
  43. and leading and trailing whitespace are removed, otherwise
  44. sep is used to split and join the words.
  45. """
  46. return (sep or ‘ ‘).join(x.capitalize() for x in s.split(sep))
  47. # Construct a translation string
  48. _idmapL = None
  49. def maketrans(fromstr, tostr):
  50. """maketrans(frm, to) -> string
  51. Return a translation table (a string of 256 bytes long)
  52. suitable for use in string.translate. The strings frm and to
  53. must be of the same length.
  54. """
  55. if len(fromstr) != len(tostr):
  56. raise ValueError, "maketrans arguments must have same length"
  57. global _idmapL
  58. if not _idmapL:
  59. _idmapL = list(_idmap)
  60. L = _idmapL[:]
  61. fromstr = map(ord, fromstr)
  62. for i in range(len(fromstr)):
  63. L[fromstr[i]] = tostr[i]
  64. return ‘‘.join(L)
  65. ####################################################################
  66. import re as _re
  67. class _multimap:
  68. """Helper class for combining multiple mappings.
  69. Used by .{safe_,}substitute() to combine the mapping and keyword
  70. arguments.
  71. """
  72. def __init__(self, primary, secondary):
  73. self._primary = primary
  74. self._secondary = secondary
  75. def __getitem__(self, key):
  76. try:
  77. return self._primary[key]
  78. except KeyError:
  79. return self._secondary[key]
  80. class _TemplateMetaclass(type):
  81. pattern = r"""
  82. %(delim)s(?:
  83. (?P%(delim)s) | # Escape sequence of two delimiters
  84. (?P%(id)s) | # delimiter and a Python identifier
  85. {(?P%(id)s)} | # delimiter and a braced identifier
  86. (?P) # Other ill-formed delimiter exprs
  87. )
  88. """
  89. def __init__(cls, name, bases, dct):
  90. super(_TemplateMetaclass, cls).__init__(name, bases, dct)
  91. if ‘pattern‘ in dct:
  92. pattern = cls.pattern
  93. else:
  94. pattern = _TemplateMetaclass.pattern % {
  95. ‘delim‘ : _re.escape(cls.delimiter),
  96. ‘id‘ : cls.idpattern,
  97. }
  98. cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE)
  99. class Template:
  100. """A string class for supporting $-substitutions."""
  101. __metaclass__ = _TemplateMetaclass
  102. delimiter = ‘$‘
  103. idpattern = r‘[_a-z][_a-z0-9]*‘
  104. def __init__(self, template):
  105. self.template = template
  106. # Search for $$, $identifier, ${identifier}, and any bare $‘s
  107. def _invalid(self, mo):
  108. i = mo.start(‘invalid‘)
  109. lines = self.template[:i].splitlines(True)
  110. if not lines:
  111. colno = 1
  112. lineno = 1
  113. else:
  114. colno = i - len(‘‘.join(lines[:-1]))
  115. lineno = len(lines)
  116. raise ValueError(‘Invalid placeholder in string: line %d, col %d‘ %
  117. (lineno, colno))
  118. def substitute(self, *args, **kws):
  119. if len(args) > 1:
  120. raise TypeError(‘Too many positional arguments‘)
  121. if not args:
  122. mapping = kws
  123. elif kws:
  124. mapping = _multimap(kws, args[0])
  125. else:
  126. mapping = args[0]
  127. # Helper function for .sub()
  128. def convert(mo):
  129. # Check the most common path first.
  130. named = mo.group(‘named‘) or mo.group(‘braced‘)
  131. if named is not None:
  132. val = mapping[named]
  133. # We use this idiom instead of str() because the latter will
  134. # fail if val is a Unicode containing non-ASCII characters.
  135. return ‘%s‘ % (val,)
  136. if mo.group(‘escaped‘) is not None:
  137. return self.delimiter
  138. if mo.group(‘invalid‘) is not None:
  139. self._invalid(mo)
  140. raise ValueError(‘Unrecognized named group in pattern‘,
  141. self.pattern)
  142. return self.pattern.sub(convert, self.template)
  143. def safe_substitute(self, *args, **kws):
  144. if len(args) > 1:
  145. raise TypeError(‘Too many positional arguments‘)
  146. if not args:
  147. mapping = kws
  148. elif kws:
  149. mapping = _multimap(kws, args[0])
  150. else:
  151. mapping = args[0]
  152. # Helper function for .sub()
  153. def convert(mo):
  154. named = mo.group(‘named‘)
  155. if named is not None:
  156. try:
  157. # We use this idiom instead of str() because the latter
  158. # will fail if val is a Unicode containing non-ASCII
  159. return ‘%s‘ % (mapping[named],)
  160. except KeyError:
  161. return self.delimiter + named
  162. braced = mo.group(‘braced‘)
  163. if braced is not None:
  164. try:
  165. return ‘%s‘ % (mapping[braced],)
  166. except KeyError:
  167. return self.delimiter + ‘{‘ + braced + ‘}‘
  168. if mo.group(‘escaped‘) is not None:
  169. return self.delimiter
  170. if mo.group(‘invalid‘) is not None:
  171. return self.delimiter
  172. raise ValueError(‘Unrecognized named group in pattern‘,
  173. self.pattern)
  174. return self.pattern.sub(convert, self.template)
  175. ####################################################################
  176. # NOTE: Everything below here is deprecated. Use string methods instead.
  177. # This stuff will go away in Python 3.0.
  178. # Backward compatible names for exceptions
  179. index_error = ValueError
  180. atoi_error = ValueError
  181. atof_error = ValueError
  182. atol_error = ValueError
  183. # convert UPPER CASE letters to lower case
  184. def lower(s):
  185. """lower(s) -> string
  186. Return a copy of the string s converted to lowercase.
  187. """
  188. return s.lower()
  189. # Convert lower case letters to UPPER CASE
  190. def upper(s):
  191. """upper(s) -> string
  192. Return a copy of the string s converted to uppercase.
  193. """
  194. return s.upper()
  195. # Swap lower case letters and UPPER CASE
  196. def swapcase(s):
  197. """swapcase(s) -> string
  198. Return a copy of the string s with upper case characters
  199. converted to lowercase and vice versa.
  200. """
  201. return s.swapcase()
  202. # Strip leading and trailing tabs and spaces
  203. def strip(s, chars=None):
  204. """strip(s [,chars]) -> string
  205. Return a copy of the string s with leading and trailing
  206. whitespace removed.
  207. If chars is given and not None, remove characters in chars instead.
  208. If chars is unicode, S will be converted to unicode before stripping.
  209. """
  210. return s.strip(chars)
  211. # Strip leading tabs and spaces
  212. def lstrip(s, chars=None):
  213. """lstrip(s [,chars]) -> string
  214. Return a copy of the string s with leading whitespace removed.
  215. If chars is given and not None, remove characters in chars instead.
  216. """
  217. return s.lstrip(chars)
  218. # Strip trailing tabs and spaces
  219. def rstrip(s, chars=None):
  220. """rstrip(s [,chars]) -> string
  221. Return a copy of the string s with trailing whitespace removed.
  222. If chars is given and not None, remove characters in chars instead.
  223. """
  224. return s.rstrip(chars)
  225. # Split a string into a list of space/tab-separated words
  226. def split(s, sep=None, maxsplit=-1):
  227. """split(s [,sep [,maxsplit]]) -> list of strings
  228. Return a list of the words in the string s, using sep as the
  229. delimiter string. If maxsplit is given, splits at no more than
  230. maxsplit places (resulting in at most maxsplit+1 words). If sep
  231. is not specified or is None, any whitespace string is a separator.
  232. (split and splitfields are synonymous)
  233. """
  234. return s.split(sep, maxsplit)
  235. splitfields = split
  236. # Split a string into a list of space/tab-separated words
  237. def rsplit(s, sep=None, maxsplit=-1):
  238. """rsplit(s [,sep [,maxsplit]]) -> list of strings
  239. Return a list of the words in the string s, using sep as the
  240. delimiter string, starting at the end of the string and working
  241. to the front. If maxsplit is given, at most maxsplit splits are
  242. done. If sep is not specified or is None, any whitespace string
  243. is a separator.
  244. """
  245. return s.rsplit(sep, maxsplit)
  246. # Join fields with optional separator
  247. def join(words, sep = ‘ ‘):
  248. """join(list [,sep]) -> string
  249. Return a string composed of the words in list, with
  250. intervening occurrences of sep. The default separator is a
  251. single space.
  252. (joinfields and join are synonymous)
  253. """
  254. return sep.join(words)
  255. joinfields = join
  256. # Find substring, raise exception if not found
  257. def index(s, *args):
  258. """index(s, sub [,start [,end]]) -> int
  259. Like find but raises ValueError when the substring is not found.
  260. """
  261. return s.index(*args)
  262. # Find last substring, raise exception if not found
  263. def rindex(s, *args):
  264. """rindex(s, sub [,start [,end]]) -> int
  265. Like rfind but raises ValueError when the substring is not found.
  266. """
  267. return s.rindex(*args)
  268. # Count non-overlapping occurrences of substring
  269. def count(s, *args):
  270. """count(s, sub[, start[,end]]) -> int
  271. Return the number of occurrences of substring sub in string
  272. s[start:end]. Optional arguments start and end are
  273. interpreted as in slice notation.
  274. """
  275. return s.count(*args)
  276. # Find substring, return -1 if not found
  277. def find(s, *args):
  278. """find(s, sub [,start [,end]]) -> in
  279. Return the lowest index in s where substring sub is found,
  280. such that sub is contained within s[start,end]. Optional
  281. arguments start and end are interpreted as in slice notation.
  282. Return -1 on failure.
  283. """
  284. return s.find(*args)
  285. # Find last substring, return -1 if not found
  286. def rfind(s, *args):
  287. """rfind(s, sub [,start [,end]]) -> int
  288. Return the highest index in s where substring sub is found,
  289. such that sub is contained within s[start,end]. Optional
  290. arguments start and end are interpreted as in slice notation.
  291. Return -1 on failure.
  292. """
  293. return s.rfind(*args)
  294. # for a bit of speed
  295. _float = float
  296. _int = int
  297. _long = long
  298. # Convert string to float
  299. def atof(s):
  300. """atof(s) -> float
  301. Return the floating point number represented by the string s.
  302. """
  303. return _float(s)
  304. # Convert string to integer
  305. def atoi(s , base=10):
  306. """atoi(s [,base]) -> int
  307. Return the integer represented by the string s in the given
  308. base, which defaults to 10. The string s must consist of one
  309. or more digits, possibly preceded by a sign. If base is 0, it
  310. is chosen from the leading characters of s, 0 for octal, 0x or
  311. 0X for hexadecimal. If base is 16, a preceding 0x or 0X is
  312. accepted.
  313. """
  314. return _int(s, base)
  315. # Convert string to long integer
  316. def atol(s, base=10):
  317. """atol(s [,base]) -> long
  318. Return the long integer represented by the string s in the
  319. given base, which defaults to 10. The string s must consist
  320. of one or more digits, possibly preceded by a sign. If base
  321. is 0, it is chosen from the leading characters of s, 0 for
  322. octal, 0x or 0X for hexadecimal. If base is 16, a preceding
  323. 0x or 0X is accepted. A trailing L or l is not accepted,
  324. unless base is 0.
  325. """
  326. return _long(s, base)
  327. # Left-justify a string
  328. def ljust(s, width, *args):
  329. """ljust(s, width[, fillchar]) -> string
  330. Return a left-justified version of s, in a field of the
  331. specified width, padded with spaces as needed. The string is
  332. never truncated. If specified the fillchar is used instead of spaces.
  333. """
  334. return s.ljust(width, *args)
  335. # Right-justify a string
  336. def rjust(s, width, *args):
  337. """rjust(s, width[, fillchar]) -> string
  338. Return a right-justified version of s, in a field of the
  339. specified width, padded with spaces as needed. The string is
  340. never truncated. If specified the fillchar is used instead of spaces.
  341. """
  342. return s.rjust(width, *args)
  343. # Center a string
  344. def center(s, width, *args):
  345. """center(s, width[, fillchar]) -> string
  346. Return a center version of s, in a field of the specified
  347. width. padded with spaces as needed. The string is never
  348. truncated. If specified the fillchar is used instead of spaces.
  349. """
  350. return s.center(width, *args)
  351. # Zero-fill a number, e.g., (12, 3) --> ‘012‘ and (-3, 3) --> ‘-03‘
  352. # Decadent feature: the argument may be a string or a number
  353. # (Use of this is deprecated; it should be a string as with ljust c.s.)
  354. def zfill(x, width):
  355. """zfill(x, width) -> string
  356. Pad a numeric string x with zeros on the left, to fill a field
  357. of the specified width. The string x is never truncated.
  358. """
  359. if not isinstance(x, basestring):
  360. x = repr(x)
  361. return x.zfill(width)
  362. # Expand tabs in a string.
  363. # Doesn‘t take non-printing chars into account, but does understand \n.
  364. def expandtabs(s, tabsize=8):
  365. """expandtabs(s [,tabsize]) -> string
  366. Return a copy of the string s with all tab characters replaced
  367. by the appropriate number of spaces, depending on the current
  368. column, and the tabsize (default 8).
  369. """
  370. return s.expandtabs(tabsize)
  371. # Character translation through look-up table.
  372. def translate(s, table, deletions=""):
  373. """translate(s,table [,deletions]) -> string
  374. Return a copy of the string s, where all characters occurring
  375. in the optional argument deletions are removed, and the
  376. remaining characters have been mapped through the given
  377. translation table, which must be a string of length 256. The
  378. deletions argument is not allowed for Unicode strings.
  379. """
  380. if deletions or table is None:
  381. return s.translate(table, deletions)
  382. else:
  383. # Add s[:0] so that if s is Unicode and table is an 8-bit string,
  384. # table is converted to Unicode. This means that table *cannot*
  385. # be a dictionary -- for that feature, use u.translate() directly.
  386. return s.translate(table + s[:0])
  387. # Capitalize a string, e.g. "aBc dEf" -> "Abc def".
  388. def capitalize(s):
  389. """capitalize(s) -> string
  390. Return a copy of the string s with only its first character
  391. capitalized.
  392. """
  393. return s.capitalize()
  394. # Substring replacement (global)
  395. def replace(s, old, new, maxsplit=-1):
  396. """replace (str, old, new[, maxsplit]) -> string
  397. Return a copy of string str with all occurrences of substring
  398. old replaced by new. If the optional argument maxsplit is
  399. given, only the first maxsplit occurrences are replaced.
  400. """
  401. return s.replace(old, new, maxsplit)
  402. # Try importing optional built-in module "strop" -- if it exists,
  403. # it redefines some string operations that are 100-1000 times faster.
  404. # It also defines values for whitespace, lowercase and uppercase
  405. # that match <ctype.h>‘s definitions.
  406. try:
  407. from strop import maketrans, lowercase, uppercase, whitespace
  408. letters = lowercase + uppercase
  409. except ImportError:
  410. pass # Use the original versions
  411. ########################################################################
  412. # the Formatter class
  413. # see PEP 3101 for details and purpose of this class
  414. # The hard parts are reused from the C implementation. They‘re exposed as "_"
  415. # prefixed methods of str and unicode.
  416. # The overall parser is implemented in str._formatter_parser.
  417. # The field name parser is implemented in str._formatter_field_name_split
  418. class Formatter(object):
  419. def format(self, format_string, *args, **kwargs):
  420. return self.vformat(format_string, args, kwargs)
  421. def vformat(self, format_string, args, kwargs):
  422. used_args = set()
  423. result = self._vformat(format_string, args, kwargs, used_args, 2)
  424. self.check_unused_args(used_args, args, kwargs)
  425. return result
  426. def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
  427. if recursion_depth < 0:
  428. raise ValueError(‘Max string recursion exceeded‘)
  429. result = []
  430. for literal_text, field_name, format_spec, conversion in \
  431. self.parse(format_string):
  432. # output the literal text
  433. if literal_text:
  434. result.append(literal_text)
  435. # if there‘s a field, output it
  436. if field_name is not None:
  437. # this is some markup, find the object and do
  438. # the formatting
  439. # given the field_name, find the object it references
  440. # and the argument it came from
  441. obj, arg_used = self.get_field(field_name, args, kwargs)
  442. used_args.add(arg_used)
  443. # do any conversion on the resulting object
  444. obj = self.convert_field(obj, conversion)
  445. # expand the format spec, if needed
  446. format_spec = self._vformat(format_spec, args, kwargs,
  447. used_args, recursion_depth-1)
  448. # format the object and append to the result
  449. result.append(self.format_field(obj, format_spec))
  450. return ‘‘.join(result)
  451. def get_value(self, key, args, kwargs):
  452. if isinstance(key, (int, long)):
  453. return args[key]
  454. else:
  455. return kwargs[key]
  456. def check_unused_args(self, used_args, args, kwargs):
  457. pass
  458. def format_field(self, value, format_spec):
  459. return format(value, format_spec)
  460. def convert_field(self, value, conversion):
  461. # do any conversion on the resulting object
  462. if conversion == ‘r‘:
  463. return repr(value)
  464. elif conversion == ‘s‘:
  465. return str(value)
  466. elif conversion is None:
  467. return value
  468. raise ValueError("Unknown converion specifier {0!s}".format(conversion))
  469. # returns an iterable that contains tuples of the form:
  470. # (literal_text, field_name, format_spec, conversion)
  471. # literal_text can be zero length
  472. # field_name can be None, in which case there‘s no
  473. # object to format and output
  474. # if field_name is not None, it is looked up, formatted
  475. # with format_spec and conversion and then used
  476. def parse(self, format_string):
  477. return format_string._formatter_parser()
  478. # given a field_name, find the object it references.
  479. # field_name: the field being looked up, e.g. "0.name"
  480. # or "lookup[3]"
  481. # used_args: a set of which args have been used
  482. # args, kwargs: as passed in to vformat
  483. def get_field(self, field_name, args, kwargs):
  484. first, rest = field_name._formatter_field_name_split()
  485. obj = self.get_value(first, args, kwargs)
  486. # loop through the rest of the field_name, doing
  487. # getattr or getitem as needed
  488. for is_attr, i in rest:
  489. if is_attr:
  490. obj = getattr(obj, i)
  491. else:
  492. obj = obj[i]
  493. return obj, first

原文地址:https://www.cnblogs.com/hello1123/p/9105393.html

时间: 2024-10-13 12:27:14

python字符串操作和string模块代码分析 牛人总结 转存的相关文章

Python 字符串操作及string模块使用

python的字符串操作通过2部分的方法函数基本上就可以解决所有的字符串操作需求: python的字符串属性函数 python的string模块 1.字符串属性方法操作: 1.>字符串格式输出对齐 1 2 3 4 5 6 7 8 9 10 11 >>> str = "Python stRING" >>> print str.center(20)       #生成20个字符长度,str排中间    Python stRING        &g

python字符串操作函数和string模块代码分析

原文链接:http://blog.chinaunix.net/uid-25992400-id-3283846.html python的字符串属性函数 字符串属性方法: >>> str='string learn' >>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute_

Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)

http://www.cnblogs.com/huangcong/archi s.strip() .lstrip() .rstrip(',') 去空格及特殊符号 复制字符串 Python 1 #strcpy(sStr1,sStr2) 2 sStr1 = 'strcpy' 3 sStr2 = sStr1 4 sStr1 = 'strcpy2' 5 print sStr2 连接字符串 Python 1 #strcat(sStr1,sStr2) 2 sStr1 = 'strcat' 3 sStr2 =

python字符串操作实方法大合集

python字符串操作实方法大合集,包括了几乎所有常用的python字符串操作,如字符串的替换.删除.截取.复制.连接.比较.查找.分割等,需要的朋友可以参考下: #1.去空格及特殊符号 s.strip().lstrip().rstrip(',') #2.复制字符串 #strcpy(sStr1,sStr2) sStr1 = 'strcpy' sStr2 = sStr1 sStr1 = 'strcpy2' print sStr2 #3.连接字符串 #strcat(sStr1,sStr2) sStr

Python字符串操作

isalnum()判断是否都是有效字符串 ? 1 2 3 4 5 6 7 8 9 10 11 12 >>> ev1 = 'evilxr' >>> ev2 = 'ev1il2xr3' >>> ev3 = '.,/[email protected]#' >>> a = ev1.isalnum() >>> print a True >>> b = ev2.isalnum() >>> pr

Python 字符串操作和元组操作

字符串操作: 字符串的 % 格式化操作: str = "Hello,%s.%s enough for ya ?" values = ('world','hot') print str % values 输出结果: Hello,world.hot enough for ya ? 模板字符串: #coding=utf-8 from string import Template ## 单个变量替换 s1 = Template('$x, glorious $x!') print s1.subs

python 字符串操作。。

#字符串操作 以0开始,有负下标的使用0第一个元素,-1最后一个元素,-len第一个元 素,len-1最后一个元素 name= "qwe , erw, qwe "print(name.index("e")) #索引 查看字符的下标 2print(name[0:4]) #切片 顾头不顾尾 qweprint(name[0::2]) #步长 qe,ew w print(name.strip()) #脱掉 qwe , erw, qweprint(name.split(&qu

转 #Python字符串操作

http://blog.chinaunix.net/uid-199788-id-99343.html #-*-coding:utf-8-*-' #Python字符串操作 '''1.复制字符串''' #strcpy(sStr1,sStr2) sStr1 = 'strcpy' sStr2 = sStr1 sStr1 = 'strcpy2' print sStr2 '''2.连接字符串''' #strcat(sStr1,sStr2) sStr1 = 'strcat' sStr2 = 'append'

Python 字符串操作,截取,长度

1.字符串操作: 字符串长度: s = "0123456"; slen = len(s); 字符串截取: print s[:-17:-1] #截取,逆序隔1个取一个字符 print s[:-17:-1] #截取,逆序隔1个取一个字符 print s[:-17:1] #截取0-倒数第17位,隔1个取一个字符 print s[:-17:-4] #截取倒数第17位-0,逆序隔4个取一个字符 print s[:-17:4] #截取0-倒数第17位,隔4个取一个字符 print s[:17:4]