Python String Objects - Part II

String Methods

In Python, expressions and built-in functions may work across a range of types, but methods are generally associated with and act upon particular objects.

Method Call Syntax

  • Attribute fetch and return object associated element(value): object.attribute
  • Function are packages of code: function(parameter)
  • Method combine attribute fetch and function at same time: object.method(parameter)

Python will first fetch the method of the object and then call it, passing in both object and the arguments. most objects have callable methods, and all are accessed using this same method-call syntax. You have to create the object before call it's method.

String Method Examples


>>> name = 'Jalo Wang'
>>> name.replace('a','A')     #It performs a global search and replace all matchs
'JAlo WAng'  
>>> name.replace('a','A',1)   #Can use the 3rd parameter to limit substitution times
'JAlo Wang'  


Each time when you try change a string, it always create a new string and assign it back to it's variable name. This incurs performance penalty. So, if you need to update a large string, better converting the string object to other objects which support in-place change:

>>> name_list = list(name)        # Use list function create a new list object
>>> name_list
['J', 'a', 'l', 'o', ' ', 'W', 'a', 'n', 'g']
>>> name_list[3] = 'x'
>>> name_list
['J', 'a', 'l', 'x', ' ', 'W', 'a', 'n', 'g']
>>> name = ''.join(name_list)     # After update, convert it back to String object
>>> name
'Jalx Wang'  


>>> name = 'Jalo,Jack,Jason'
>>> name.split(',')               # Splits the string by comma
['Jalo', 'Jack', 'Jason']         # Returns a list

Use dir(str) and help(str.method) for more string methods information:

>>> dir(str)
[... 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith'...]
>>> help(str.rfind)
Help on method_descriptor:

    S.rfind(sub[, start[, end]]) -> int

    Return the highest 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.

String Formatting Expressions

String Formatting allows us to perform multiple type-specific substitutions on a string in a single step.

String Formatting is available in two syntax in Python today:

expressions style: '...%s...' % (values) method style: '...{}...'.format(values)

Basic Formatting Expression

expressions style: '...%s...' % (values)

The % operator provides a simple way to format values as strings according to a format definition. It's a compact way to code multiple string substitutions all at once, instead of building and concatenating parts individually.

The % formatting expression operator expects either a single item or a tuple of one or more items on its right side.

>>> '%s is %d-%d-%d' % ('today',2016,6,14)
'today is 2016-6-14'  

%s is often the only code you need to remember for the formatting expression.

Advanced Formatting Expression

syntax: %[(keyname)][flags][width][.precision]typecode

​ 'keyname' is for dictionary-based formatting Expression use.

  • This example formats integers by default, and then in a six-character field with left justification and zero padding:
>>> x = 1234
# d Decimal (base-10 integer)
# - left justification
# 6 width
# 0 zero padding
>>> res = 'integers: ...%d...%−6d...%06d' % (x, x, x)
>>> res
'integers: ...1234...1234  ...001234'  
  • When sizes are not known until runtime, you can use a computed width and precision by specifying them with a * in the format string to force their values to be taken from the next item in the inputs to the right of the % operator—the 4 in the tuple here gives precision:
>>> '%.*f' % (4, 1/3.0)
>>> "%*.*f" % (10,4,100/3.0)
'   33.3333'  

Dictionary-Based Formatting Expressions

  • String formatting allows conversion targets from a dictionary index and fetch the corresponding values:
>>> '%(qty)d more %(food)s' % {'qty': 1, 'food': 'spam'}
'1 more spam'  
  • This trick is also used in conjunction with the vars() function, which returns a dictionary containing all the variables that exist in the place:
>>> location = 'Shanghai'
>>> country = 'China'
>>> print ("Hello, I live in %(location)s, %(country)s" % vars())
Hello, I live in Shanghai, China