Advertisement
here2share

-- String Reference

Feb 8th, 2015
425
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.21 KB | None | 0 0
  1. -- String Reference
  2.  
  3. center(width[, fillchar]) - Center in a string of given length.
  4.  
  5. 'juggler'.center(50)
  6. '                     juggler                      '
  7. 'juggler'.center(50,'-')
  8. '---------------------juggler----------------------'
  9. count(sub[, start[, end]]) - Return the number of occurrences of substring sub in string S[start:end].
  10.  
  11. "abca".count('a')   # 2
  12. decode([encoding[, errors]]) - Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is ‘strict’, meaning that encoding errors raise UnicodeError. Other possible values are ‘ignore’, ‘replace’ and any other name registered via codecs.register_error, see section 4.9.1 of Python LibRef.
  13.  
  14. "abc".decode()                          # u'abc'
  15. "abc".decode("utf-8")                   # u'abc'
  16. 'āb'.decode('ascii', 'ignore')    # b
  17. 'āb'.decode('ascii', 'replace')   # ��b
  18. encode([encoding[,errors]]) - Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme.
  19.  
  20. u'abc'.encode()         # 'abc' [default is ascii]
  21. u'abc'.encode("utf-8")  # 'abc'
  22. endswith(suffix[, start[, end]]) - Return True if the string ends with the specified suffix, otherwise return False. startswith() is the same but from beginning of the string.
  23.  
  24. "abc".endswith("bc")   # True
  25. "abc".endswith("zz")   # False
  26. expandtabs([tabsize]) - Return a copy of the string where all tab characters are expanded using spaces.
  27.  
  28. '\tabc'.expandtabs(4)   # "    abc"
  29. find(sub[, start[, end]]) - Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end].
  30.  
  31. "abcdef".find("b")   # 1
  32. "abcdef".find("e")   # 4
  33. "abcdef".find("z")   # -1
  34. index(sub[, start[, end]]) - Like find(), but raise ValueError when the substring is not found.
  35.  
  36. "abcdef".index("z")   # [ValueError raised]
  37. isalnum() - Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise.
  38.  
  39. "abc4".isalnum()    # True
  40. "1234".isalnum()    # True
  41. ";".isalnum()       # False
  42. " ".isalnum()       # False
  43. "".isalnum()        # False
  44. isalpha() - Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
  45.  
  46. "abc".isalpha()     # True
  47. "abc4".isalpha()    # False
  48. " ".isalpha()       # False
  49. "".isalpha()        # False
  50. isdigit() - Return true if all characters in the string are digits and there is at least one character, false otherwise.
  51.  
  52. "123".isdigit()     # True
  53. "abc".isdigit()     # False
  54. "".isdigit()        # False
  55. islower() - Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
  56.  
  57. "abc".islower()   # True
  58. "123".islower()   # False
  59. "Abc".islower()   # False
  60. isspace() - Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.
  61.  
  62. "abc".isspace()     # False
  63. " ".isspace()       # True
  64. "\t \n".isspace()   # True
  65. "".isspace()        # False
  66. istitle() - Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise.
  67.  
  68. "Abc".istitle()         # True
  69. "abc".istitle()         # False
  70. "Abc Abc".istitle()     # True
  71. "Abc abc".istitle()     # False
  72. isupper() - Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.
  73.  
  74. "".isupper()        # False
  75. "Abc".isupper()     # False
  76. "ABC".isupper()     # True
  77. join(seq) - Return a string which is the concatenation of the strings in the sequence seq. The separator between elements is the string providing this method.
  78.  
  79. ",".join("abc")   # "a,b,c"
  80. ljust(width[, fillchar]) - Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s). rjust() is the same but justifies on the right side.
  81.  
  82. "abc".ljust(5)   # "abc  "
  83. "abc".ljust(2)   # "abc"
  84. lower() - Return a copy of the string converted to lowercase. upper() is the same but converts to upper case.
  85.  
  86. "ABcd".lower()   # "abcd"
  87. lstrip([chars]) - Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. rstrip() is the same but on the right side.
  88.  
  89. '   spacious   '.lstrip()          # 'spacious   '
  90. '..,example..,'.lstrip('.,')       # 'example..,'
  91. replace(old, new[, count]) - Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
  92.  
  93. "monster".replace("o", "ue")   # "muenster"
  94. "baobab".replace("b", "t", 1)  # "taobab"
  95. rfind(sub [,start [,end]]) - Return the highest index in the string 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. rindex() is the same but raises ValueError if substring is not found.
  96.  
  97. "juggler".rfind("le")   # 4
  98. "juggler".rfind("ze")   # -1
  99. split([sep [,maxsplit]]) - Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split().
  100.  
  101. "a b c".split()                 # ['a', 'b', 'c']
  102. "a,b,c".split(",")              # ['a', 'b', 'c']
  103. "".split()                      # []
  104. "a b c d e f".split(" ", 2)     # ['a', 'b', 'c d e f']
  105. "a b c d e f".rsplit(" ", 2)    # ['a b c d', 'e', 'f']
  106. splitlines([keepends]) - Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.
  107.  
  108. 'a\nb\nc\n'.splitlines()        # ['a', 'b', 'c']
  109. 'a\nb\nc\n'.splitlines(True)    # ['a\n', 'b\n', 'c\n']
  110. strip([chars]) - Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
  111.  
  112. '   spacious   '.strip()           # 'spacious'
  113. '..example,,'.strip(',.')          # 'example'
  114. swapcase() - Return a copy of the string with uppercase characters converted to lowercase and vice versa.
  115.  
  116. "tRaPeze".swapcase()   # "TrApEZE"
  117. title() - Return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase. Unlike string.capwords this function will lowercase the rest of each word.
  118.  
  119. 'tigers jumping through hoops'.title()
  120. # 'Tigers Jumping Through Hoops'
  121. 'tigErs jUmping througH hooPS'.title()
  122. # 'Tigers Jumping Through Hoops'
  123. translate(table[, deletechars]) - Return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. For Unicode objects, the translate() method does not accept the optional deletechars argument. Instead, it returns a copy of the s where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted. Note, a more flexible approach is to create a custom character mapping codec using the codecs module (see encodings.cp1251 for an example).
  124.  
  125. tbl = maketrans("ab", "yz")
  126. "about".translate(tbl)          # "yzout"
  127. zfill(width) - Return the numeric string left filled with zeros in a string of length width. The original string is returned if width is less than len(s).
  128.  
  129. "5".zfill(3) + ".txt"   # "005.txt"
  130. "5:00".zfill(5)         # "05:00"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement