Python Language


String Methods All Versions

Python 2.x

2.0
2.1
2.2
2.3
2.4
2.5
2.6
2.7

Python 3.x

3.0
3.1
3.2
3.3
3.4
3.5
3.6

This draft deletes the entire topic.

Introduction

Introduction

expand all collapse all

Examples

  • 15

    Python's string type provides many functions that act on the capitalization of a string. These include :

    • str.casefold
    • str.upper
    • str.lower
    • str.capitalize
    • str.title
    • str.swapcase

    With unicode strings (the default in Python 3), these operations are not 1:1 mappings or reversible. Most of these operations are intended for display purposes, rather than normalization.


    Python 3.x3.3

    str.casefold()

    str.casefold creates a lowercase string that is suitable for case insensitive comparisons. This is more aggressive than str.lower and may modify strings that are already in lowercase or cause strings to grow in length, and is not intended for display purposes.

    "XßΣ".casefold()
    # 'xssσ'
    
    "XßΣ".lower()
    # 'xßς'
    

    The transformations that take place under casefolding are defined by the Unicode Consortium in the CaseFolding.txt file on their website.


    str.upper()

    str.upper takes every character in a string and converts it to its uppercase equivalent, for example:

    "This is a 'string'.".upper()
    # "THIS IS A 'STRING'."
    

    str.lower()

    str.lower does the opposite; it takes every character in a string and converts it to its lowercase equivalent:

    "This IS a 'string'.".lower()
    # "this is a 'string'."
    

    str.capitalize()

    str.capitalize returns a capitalized version of the string, that is, it makes the first character have upper case and the rest lower:

    "this Is A 'String'.".capitalize() # Capitalizes the first character and lowercases all others
    # "This is a 'string'."
    

    str.title()

    str.title returns the title cased version of the string, that is, every letter in the beginning of a word is made upper case and all others are made lower case:

    "this Is a 'String'".title()
    # "This Is A 'String'"
    

    str.swapcase()

    str.swapcase returns a new string object in which all lower case characters are swapped to upper case and all upper case characters to lower:

    "this iS A STRiNG".swapcase() #Swaps case of each character
    # "THIS Is a strIng"
    

    Usage as str class methods

    It is worth noting that these methods may be called either on string objects (as shown above) or as a class method of the str class (with an explicit call to str.upper, etc.)

    str.upper("This is a 'string'")
    # "THIS IS A 'STRING'"
    

    This is most useful when applying one of these methods to many strings at once in say, a map function.

    map(str.upper,["These","are","some","'strings'"])
    # ['THESE', 'ARE', 'SOME', "'STRINGS'"]
    
  • 11

    Python supports a translate method on the str type which allows you to specify the translation table (used for replacements) as well as any characters which should be deleted in the process.

    str.translate(table[, deletechars])
    
    ParameterDescription
    tableIt is a lookup table that defines the mapping from one character to another.
    deletecharsA list of characters which are to be removed from the string.

    The maketrans method (str.maketrans in Python 3 and string.maketrans in Python 2) allows you to generate a translation table.

    translation_table = str.maketrans("aeiou", "12345")
    my_string = "This is a string!"
    translated = my_string.translate(translation_table)
    # out: 'Th3s 3s 1 str3ng!'
    

    The translate method returns a string which is a translated copy of the original string.


    You can set the table argument to None if you only need to delete characters.

    'this syntax is very useful'.translate(None, 'aeiou')
    # Out: 'ths syntx s vry sfl'
    
  • 8

    Python provides string interpolation and formatting functionality through the str.format function, introduced in version 2.6.

    Given the following variables:

    i = 10
    f = 1.5
    s = "foo"
    l = ['a', 1, 2]
    d = {'a': 1, 2: 'foo'}
    

    The following statements are all equivalent

    "10 1.5 foo ['a', 1, 2] {'a': 1, 2: 'foo'}"
    
    "{} {} {} {} {}".format(i, f, s, l, d)
    
    str.format("{} {} {} {} {}", i, f, s, l, d)
    
    "{0} {1} {2} {3} {4}".format(i, f, s, l, d)
    
    "{0:d} {1:0.1f} {2} {3!r} {4!r}".format(i, f, s, l, d)
    
    "{i:d} {f:0.1f} {s} {l!r} {d!r}".format(i=i, f=f, s=s, l=l, d=d)
    

    For reference, Python also supports C-style qualifiers for string formatting. The examples below are equivalent to those above, but the str.format versions are preferred due to benefits in flexibility, consistency of notation, and extensibility:

    "%d %0.1f %s %r %r" % (i, f, s, l, d)
    
    "%(i)d %(f)0.1f %(s)s %(l)r %(d)r" % dict(i=i, f=f, s=s, l=l, d=d)
    

    The braces uses for interpolation in str.format can also be numbered to reduce duplication when formatting strings. For example, the following are equivalent:

    "I am from Australia. I love cupcakes from Australia!"
    
    "I am from {}. I love cupcakes from {}!".format("Australia", "Australia")
    
    "I am from {0}. I love cupcakes from {0}!".format("Australia")
    

    While the official python documentation is, as usual, thorough enough, pyformat.info has a great set of examples with detailed explanations.

    Additionally, the { and } characters can be escaped by using double brackets:

    desired output: "{'a': 5, 'b': 6}"
    code:           print "{{'{}': {}, '{}': {}}}".format("a", 5, "b", 6)
    

    See String Formatting for additional information. str.format() was proposed in PEP 3101.

Please consider making a request to improve this example.

Syntax

  • str.capitalize() -> str
  • str.casefold() -> str [only for Python > 3.3]
  • str.center(width[, fillchar]) -> str
  • str.count(sub[, start[, end]]) -> int
  • str.decode(encoding="utf-8"[, errors]) -> unicode [only in Python 2.x]
  • str.encode(encoding="utf-8", errors="strict") -> bytes
  • str.endswith(suffix[, start[, end]]) -> bool
  • str.expandtabs(tabsize=8) -> str
  • str.find(sub[, start[, end]]) -> int
  • str.format(*args, **kwargs) -> str
  • str.format_map(mapping) -> str
  • str.index(sub[, start[, end]]) -> int
  • str.isalnum() -> bool
  • str.isalpha() -> bool
  • str.isdecimal() -> bool
  • str.isdigit() -> bool
  • str.isidentifier() -> bool
  • str.islower() -> bool
  • str.isnumeric() -> bool
  • str.isprintable() -> bool
  • str.isspace() -> bool
  • str.istitle() -> bool
  • str.isupper() -> bool
  • str.join(iterable) -> str
  • str.ljust(width[, fillchar]) -> str
  • str.lower() -> str
  • str.lstrip([chars]) -> str
  • static str.maketrans(x[, y[, z]])
  • str.partition(sep) -> (head, sep, tail)
  • str.replace(old, new[, count]) -> str
  • str.rfind(sub[, start[, end]]) -> int
  • str.rindex(sub[, start[, end]]) -> int
  • str.rjust(width[, fillchar]) -> str
  • str.rpartition(sep) -> (head, sep, tail)
  • str.rsplit(sep=None, maxsplit=-1) -> list of strings
  • str.rstrip([chars]) -> str
  • str.split(sep=None, maxsplit=-1) -> list of strings
  • str.splitlines([keepends]) -> list of strings
  • str.startswith(prefix[, start[, end]]) -> book
  • str.strip([chars]) -> str
  • str.swapcase() -> str
  • str.title() -> str
  • str.translate(table) -> str
  • str.upper() -> str
  • str.zfill(width) -> str

Parameters

Parameters

Remarks

String objects are immutable, meaning that they can't be modified in place the way a list can. Because of this, methods on the built-in type str always return a new str object, which contains the result of the method call.

Still have a question about String Methods? Ask Question

Topic Outline