Skip to content
Search

Python:String

lastmod 2018-10-03created 2015-03-0117 edits

Notes on Python strings.

String literals

The r prefix makes a raw string, which leaves backslashes uninterpreted, so it is useful for things like regular expressions. For example, without the r prefix you would have to write

re.compile('(\\d+)/(\\d+)/(\\d+)')

which is long and inconvenient because every backslash must be doubled. That is why the r prefix is usually added.

Functions

  • split(param1): Splits a string. Splits on the param1 string.
  • find: Finds a string.
  • rfind: Finds a string in reverse order.
  • strip: Removes leading and trailing whitespace (Trim).
  • replace: Replaces a string.

Replace

a = "Life is too short"
a.replace("Life", "Your leg")

Use Regexp

import re
article = re.sub(r'(?is)</html>.+', '</html>', article)

Format string

Format strings are applied as follows.

print "Result: {0}, {1}".format(string1, string2)

Or

print "Result: %s, %s" % (config.version, VERSION_MIN)

Insert string

Insert a string as follows.

def insert_dash(string, index):
    return string[:index] + '-' + string[index:]

print insert_dash("355879ACB6", 5)

Multiline strings

To spread a string across multiple lines, use the following.

string = """line one
line two
line three"""

Or

string = ("this is an "
    "implicitly joined "
    "string")

Or

string = "this is an " + \
    "implicitly joined " + \
    "string"

Or

string = "this is an " \
    "implicitly joined " \
    "string"

Favorite site

References


  1. Jump_to_Python_-_String.pdf ↩

author Zer0 sitemap