Python String Methods

Part of the Python For Dummies Cheat Sheet

The following list shows you how to perform common string methods, or actions on a string, in Python. Type the specific order to achieve the desired result.

Syntax Action
S.count(substring[, start[, end]]) Count occurrences of substring
S.decode([encoding]) Decode to Unicode using default encoding
S.encode([encoding]) Encode from Unicode using default encoding
S.endswith(suffix[, start[, end]]) True if S ends with suffix
S.find(substring [,start [,end]]) Find first occurrence of substring and return its index number; if not found, return -1
S.index(substring [,start [,end]]) Find first occurrence of substring and return its index number; if not found, raise ValueError
S.isalnum() True if S has only alphanumeric characters
S.isalpha() True if S has only alphabetic characters
S.isdigit() True if S has only digits
S.isspace() True if S has only whitespace characters
S.join(iterable) Using S as a separator, stick together the strings in iterable
S.lower() Convert S to lowercase
S.lstrip([chars]) Remove whitespace (or chars) from front (left) of S
S.replace (old, new[, count]) Replace old (a substring) with new
S.rfind(substring [,start [,end]]) Find the last (rightmost) occurrence of substring and return its index number; if not found, return -1
S.rindex(substring [,start [,end]]) Find the last (rightmost) occurrence of substring and returns its index number; if not found, raise ValueError
S.rstrip([chars]) Remove whitespace (or chars) from end (right) of S
S.split([separator [,maxsplit]]) Split S using whitespace (or separator) and return a list of substrings
S.startswith(prefix[, start[, end]]) True if S starts with prefix
S.strip([chars]) Remove characters at beginning and end of S; default is whitespace characters
S.upper() Convert S to uppercase
Note: String methods that change a string always return a copy; the original string remains unchanged.
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus

SERIES
Python For Dummies Cheat Sheet

Advertisement

Inside Dummies.com