Python string Module

The string module in Python provides a variety of functions and constants that are useful for working with strings. It offers utility functions for string operations and constants that can be used to customize and format strings. This module is part of Python’s standard library, so it can be used without the need for additional installation.

Table of Contents

  1. Introduction
  2. Constants in the string Module
    • ascii_letters
    • ascii_lowercase
    • ascii_uppercase
    • digits
    • hexdigits
    • octdigits
    • punctuation
    • printable
    • whitespace
  3. Utility Functions in the string Module
    • capwords
    • Template
  4. Built-in String Methods
    • capitalize()
    • casefold()
    • center()
    • count()
    • encode()
    • endswith()
    • find()
    • format()
    • index()
    • isalnum()
    • isalpha()
    • isascii()
    • isdecimal()
    • isdigit()
    • isidentifier()
    • islower()
    • isnumeric()
    • isprintable()
    • isspace()
    • istitle()
    • isupper()
    • join()
    • ljust()
    • lower()
    • lstrip()
    • partition()
    • replace()
    • rfind()
    • rindex()
    • rjust()
    • rpartition()
    • rsplit()
    • rstrip()
    • split()
    • splitlines()
    • startswith()
    • strip()
    • swapcase()
    • title()
    • upper()
    • zfill()
  5. Examples
    • Using Constants
    • Using capwords
    • Using Template
    • Using Built-in String Methods
  6. Conclusion
  7. References

Introduction

The string module provides a range of functions and constants for working with strings. Whether you’re looking to access a predefined set of characters or perform common string manipulations, this module has you covered.

Constants in the string Module

The string module includes several constants that provide sets of characters commonly used in string operations.

ascii_letters

A string containing all ASCII letters, both uppercase and lowercase.

import string

print(string.ascii_letters)

Output:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

ascii_lowercase

A string containing all lowercase ASCII letters.

import string

print(string.ascii_lowercase)

Output:

abcdefghijklmnopqrstuvwxyz

ascii_uppercase

A string containing all uppercase ASCII letters.

import string

print(string.ascii_uppercase)

Output:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

digits

A string containing all decimal digits.

import string

print(string.digits)

Output:

0123456789

hexdigits

A string containing all hexadecimal digits.

import string

print(string.hexdigits)

Output:

0123456789abcdefABCDEF

octdigits

A string containing all octal digits.

import string

print(string.octdigits)

Output:

01234567

punctuation

A string containing all punctuation characters.

import string

print(string.punctuation)

Output:

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

printable

A string containing all characters that are printable.

import string

print(string.printable)

Output:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 	



whitespace

A string containing all whitespace characters.

import string

print(string.whitespace)

Output:

 	



Utility Functions in the string Module

The string module provides several utility functions for string operations.

capwords

The capwords function capitalizes the first letter of each word in a string and converts the rest of the letters to lowercase.

import string

s = "hello world"
print(string.capwords(s))

Output:

Hello World

Template

The Template class allows for string substitution using placeholders.

from string import Template

t = Template('Hello, $name!')
print(t.substitute(name='John'))

Output:

Hello, John!

Built-in String Methods

Python provides numerous built-in methods for string manipulation. Here are some of the most commonly used methods:

capitalize()

Capitalizes the first character of the string.

s = "hello"
print(s.capitalize())

Output:

Hello

casefold()

Converts the string to lowercase, suitable for caseless comparisons.

s = "HELLO"
print(s.casefold())

Output:

hello

center()

Centers the string within the specified width, padding with spaces or a specified character.

s = "hello"
print(s.center(10, '*'))

Output:

**hello***

count()

Counts the number of occurrences of a substring in the string.

s = "hello world"
print(s.count('l'))

Output:

3

encode()

Encodes the string using the specified encoding.

s = "hello"
print(s.encode('utf-8'))

Output:

b'hello'

endswith()

Returns True if the string ends with the specified suffix.

s = "hello"
print(s.endswith('o'))

Output:

True

find()

Returns the lowest index of the substring if it is found in the string.

s = "hello"
print(s.find('l'))

Output:

2

format()

Formats the string using the specified arguments.

s = "Hello, {}!"
print(s.format('John'))

Output:

Hello, John!

index()

Returns the lowest index of the substring if it is found in the string. Raises a ValueError if the substring is not found.

s = "hello"
print(s.index('l'))

Output:

2

isalnum()

Returns True if all characters in the string are alphanumeric.

s = "hello123"
print(s.isalnum())

Output:

True

isalpha()

Returns True if all characters in the string are alphabetic.

s = "hello"
print(s.isalpha())

Output:

True

isascii()

Returns True if all characters in the string are ASCII.

s = "hello"
print(s.isascii())

Output:

True

isdecimal()

Returns True if all characters in the string are decimal characters.

s = "123"
print(s.isdecimal())

Output:

True

isdigit()

Returns True if all characters in the string are digits.

s = "123"
print(s.isdigit())

Output:

True

isidentifier()

Returns True if the string is a valid identifier.

s = "hello"
print(s.isidentifier())

Output:

True

islower()

Returns True if all characters in the string are lowercase.

s = "hello"
print(s.islower())

Output:

True

isnumeric()

Returns True if all characters in the string are numeric.

s = "123"
print(s.isnumeric())

Output:

True

isprintable()

Returns True if all characters in the string are printable.

s = "hello"
print(s.isprintable())

Output:

True

isspace()

Returns True if all characters in the string are whitespace.

s = "   "
print(s.isspace())

Output:

True

istitle()

Returns True if the string is title-cased.

s = "Hello World"
print(s.istitle())

Output:

True

isupper()

Returns True if all characters in the string are uppercase.


python
s = "HELLO"
print(s.isupper())

join()

Joins the elements of an iterable with the string as a separator.

s = "-"
print(s.join(['hello', 'world']))

Output:

hello-world

ljust()

Left-justifies the string within the specified width, padding with spaces or a specified character.

s = "hello"
print(s.ljust(10, '*'))

Output:

hello*****

lower()

Converts all characters in the string to lowercase.

s = "HELLO"
print(s.lower())

Output:

hello

lstrip()

Removes leading whitespace or specified characters from the string.

s = "  hello"
print(s.lstrip())

Output:

hello

partition()

Splits the string at the first occurrence of the separator and returns a tuple.

s = "hello world"
print(s.partition(' '))

Output:

('hello', ' ', 'world')

replace()

Replaces occurrences of a substring with another substring.

s = "hello world"
print(s.replace('world', 'Python'))

Output:

hello Python

rfind()

Returns the highest index of the substring if it is found in the string.

s = "hello"
print(s.rfind('l'))

Output:

3

rindex()

Returns the highest index of the substring if it is found in the string. Raises a ValueError if the substring is not found.

s = "hello"
print(s.rindex('l'))

Output:

3

rjust()

Right-justifies the string within the specified width, padding with spaces or a specified character.

s = "hello"
print(s.rjust(10, '*'))

Output:

*****hello

rpartition()

Splits the string at the last occurrence of the separator and returns a tuple.

s = "hello world"
print(s.rpartition(' '))

Output:

('hello', ' ', 'world')

rsplit()

Splits the string at the specified separator and returns a list.

s = "hello world"
print(s.rsplit())

Output:

['hello', 'world']

rstrip()

Removes trailing whitespace or specified characters from the string.

s = "hello  "
print(s.rstrip())

Output:

hello

split()

Splits the string at the specified separator and returns a list.

s = "hello world"
print(s.split())

Output:

['hello', 'world']

splitlines()

Splits the string at line breaks and returns a list.

s = "hello\nworld"
print(s.splitlines())

Output:

['hello', 'world']

startswith()

Returns True if the string starts with the specified prefix.

s = "hello"
print(s.startswith('h'))

Output:

True

strip()

Removes leading and trailing whitespace or specified characters from the string.

s = "  hello  "
print(s.strip())

Output:

hello

swapcase()

Converts uppercase characters to lowercase and vice versa.

s = "Hello World"
print(s.swapcase())

Output:

hELLO wORLD

title()

Converts the first character of each word to uppercase and the remaining characters to lowercase.

s = "hello world"
print(s.title())

Output:

Hello World

upper()

Converts all characters in the string to uppercase.

s = "hello"
print(s.upper())

Output:

HELLO

zfill()

Pads the string with zeros on the left to the specified width.

s = "42"
print(s.zfill(5))

Output:

00042

Examples

Using Constants

You can use the constants from the string module to check if a character belongs to a specific set.

import string

char = 'a'
if char in string.ascii_letters:
    print(f"'{char}' is a letter.")

Output:

'a' is a letter.

Using capwords

Capitalize the first letter of each word in a sentence.

import string

sentence = "the quick brown fox"
capitalized_sentence = string.capwords(sentence)
print(capitalized_sentence)

Output:

The Quick Brown Fox

Using Template

Create a template and substitute placeholders with values.

from string import Template

template = Template('Hi, $name! Welcome to $place.')
result = template.substitute(name='Alice', place='Wonderland')
print(result)

Output:

Hi, Alice! Welcome to Wonderland.

Using Built-in String Methods

Combine built-in string methods with string module constants for complex operations.

import string

s = " hello, world! 123 "
cleaned = s.strip().capitalize().replace('world', 'Python')
print(cleaned)

if cleaned.startswith('Hello'):
    print(f"Cleaned string starts with 'Hello'.")

Output:

Hello, Python! 123
Cleaned string starts with 'Hello'.

Conclusion

The string module in Python provides a comprehensive set of constants, utility functions, and methods for working with strings. From constants that offer predefined sets of characters to utility functions for common string manipulations and numerous built-in string methods, this module is a valuable resource for anyone working with text data. Whether you need to format strings, check character sets, or perform substitutions, the string module has you covered.

References

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top