Skip to content

Python String Methods

Python’s built-in str class defines different methods. These methods can be used to manipulate strings. In this tutorial, we will learn about the different methods available for Python strings.

These are some of the most commonly used string methods:

Section titled “These are some of the most commonly used string methods:”
Sequence
Function Name
Description
1capitalize()Converts the first character to upper case
2casefold()Converts string into lower case
3center()Returns a centered string
4count()Returns the number of times a specified value occurs in a string
5encode()Returns an encoded version of the string
6endswith()Returns true if the string ends with the specified value
7expandtabs()Sets the tab size of the string
8find()Searches the string for a specified value and returns the position of where it was found
9format()Formats specified values in a string
10format_map()Formats specified values in a string
11index()Searches the string for a specified value and returns the position of where it was found
12isalnum()Returns True if all characters in the string are alphanumeric
13isalpha()Returns True if all characters in the string are in the alphabet
14isdecimal()Returns True if all characters in the string are decimals
15isdigit()Returns True if all characters in the string are digits
16isidentifier()Returns True if the string is an identifier
17islower()Returns True if all characters in the string are lower case
18isnumeric()Returns True if all characters in the string are numeric
19isprintable()Returns True if all characters in the string are printable
20isspace()Returns True if all characters in the string are whitespaces
21istitle()Returns True if the string follows the rules of a title
22isupper()Returns True if all characters in the string are upper case
23join()Joins the elements of an iterable to the end of the string
24ljust()Returns a left justified version of the string
25lower()Converts a string into lower case
26lstrip()Returns a left trim version of the string
27maketrans()Returns a translation table to be used in translations
28partition()Returns a tuple where the string is parted into three parts
29replace()Returns a string where a specified value is replaced with a specified value
30rfind()Searches the string for a specified value and returns the last position of where it was found
31rindex()Searches the string for a specified value and returns the last position of where it was found
32rjust()Returns a right justified version of the string
33rpartition()Returns a tuple where the string is parted into three parts
34rsplit()Splits the string at the specified separator, and returns a list
35rstrip()Returns a right trim version of the string
36split()Splits the string at the specified separator, and returns a list
37splitlines()Splits the string at line breaks and returns a list
38startswith()Returns true if the string starts with the specified value
39strip()Returns a trimmed version of the string
40swapcase()Swaps cases, lower case becomes upper case and vice versa
41title()Converts the first character of each word to upper case
42translate()Returns a translated string
43upper()Converts a string into upper case
44zfill()Fills the string with a specified number of 0 values at the beginning
45+Concatenates two strings
46*Returns a string repeated the specified number of times
47[]Returns the character at the specified index
48[:]Returns the slice from the specified index to the specified index
49inReturns True if a sequence with the specified value is present in the object
50not inReturns True if a sequence with the specified value is not present in the object
51%Formats specified values in a string
52<Returns True if the first string is lower than the second string
53<=Returns True if the first string is lower than or equal to the second string
54>Returns True if the first string is greater than the second string
55>=Returns True if the first string is greater than or equal to the second string
56==Returns True if the first string is equal to the second string
57!=Returns True if the first string is not equal to the second string
58ord()Converts a character into Unicode
59hex()Converts an integer to a hexadecimal string
60oct()Converts an integer to an octal string
61bin()Converts an integer to a binary string
62chr()Converts an integer to a character
63len()Returns the length of the string
64repr()Returns a readable version of the string
65ascii()Returns a readable version of the string
66max()Returns the largest character in the string
67min()Returns the smallest character in the string
68str()Returns a string object
69type()Returns the type of the specified object
70help()Executes the built-in help system
diagram strip removes characters, not a prefix or a suffix mermaid
The argument is a SET of characters to shave off each end, repeatedly, in any order -- not a piece of text to delete. So stripping '.com' also removes any leading or trailing c, o, m or dot, which is why it silently damages ordinary strings. removeprefix and removesuffix do the literal thing people usually mean.
diagram split with no argument and split with one behave differently mermaid
These are two algorithms sharing a name. With no argument, runs of whitespace collapse and the ends are trimmed, which is what you want for prose. With a separator, every occurrence divides, so consecutive separators produce empty fields -- which is what you want for a CSV line, where an empty field is meaningful.

The capitalize() method returns a string where the first character is upper case.

Syntax:

  • Returns - A capitalized string

Example:

strings.py
# capitalize() method
string = 'python strings'
print(string.capitalize())

Output

command
C:\Users\Your Name> python strings.py
Python strings

The casefold() method returns a string where all the characters are lower case.

Syntax:

  • Returns - A lower case string

Example:

strings.py
# casefold() method
string = 'Python Strings'
print(string.casefold())

Output

command
C:\Users\Your Name> python strings.py
python strings

The center() method will center align the string, using a specified character (space is default) as the fill character.

Syntax:

  • length - The length of the returned string
  • character (optional) - The character to fill the missing space on each side. Default is " "
  • Returns - A centered string

Example:

strings.py
# center() method
string = 'Python Strings'
print(string.center(20))
print(string.center(20, '*'))

Output

command
C:\Users\Your Name> python strings.py
   Python Strings
***Python Strings***

The count() method returns the number of times a specified value appears in the string.

Syntax:

  • value - The value to search for
  • start (optional) - The position to start the search. Default is 0
  • end (optional) - The position to end the search. Default is len(string)
  • Returns - The number of times the value appears in the string

Example:

strings.py
# count() method
string = 'Python Strings'
print(string.count('s'))
print(string.count('s', 7, 14))

Output

command
C:\Users\Your Name> python strings.py
2
1

The encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.

Syntax:

  • encoding (optional) - A String specifying the encoding to use. Default is UTF-8
  • errors (optional) - A String specifying the error method. Legal values are:
    • backslashreplace - uses a backslash instead of the character that could not be encoded
    • ignore - ignores the characters that cannot be encoded
    • namereplace - replaces the character with a text explaining the character
    • strict - Default, raises an error on failure
    • replace - replaces the character with a questionmark
    • xmlcharrefreplace - replaces the character with an xml character

Example:

strings.py
# encode() method
string = 'Python Strings'
print(string.encode())
print(string.encode(encoding='ascii', errors='ignore'))

Output

command
C:\Users\Your Name> python strings.py
b'Python Strings'
b'Python Strings'

The endswith() method returns True if the string ends with the specified value, otherwise False.

Syntax:

  • value - Required. The value to check if the string ends with
  • start (optional) - Optional. An Integer specifying at which position to start the search
  • end (optional) - Optional. An Integer specifying at which position to end the search
  • Returns - True if the string ends with the specified value, otherwise False

Example:

strings.py
# endswith() method
string = 'Python Strings'
print(string.endswith('s'))
print(string.endswith('s', 7, 14))

Output

command
C:\Users\Your Name> python strings.py
True
False

The expandtabs() method sets the tab size to the specified number of whitespaces.

Syntax:

  • tabsize (optional) - A number specifying the tabsize. Default tabsize is 8
  • Returns - A string where all \t characters are replaced with whitespaces using the specified tabsize

Example:

strings.py
# expandtabs() method
string = 'Python\tStrings'
print(string.expandtabs())
print(string.expandtabs(2))
print(string.expandtabs(4))

Output

command
C:\Users\Your Name> python strings.py
Python  Strings
Python  Strings
Python    Strings

The find() method finds the first occurrence of the specified value. The find() method returns -1 if the value is not found.

Syntax:

  • value - Required. The value to search for
  • start (optional) - Optional. Where to start the search. Default is 0
  • end (optional) - Optional. Where to end the search. Default is len(string)
  • Returns - The index of the first occurrence of the specified value

Example:

strings.py
# find() method
string = 'Python Strings'
print(string.find('s'))
print(string.find('s', 7, 14))

Output

command
C:\Users\Your Name> python strings.py
7
-1

The format() method formats the specified value(s) and insert them inside the string’s placeholder.

Syntax:

  • value1, value2… - Optional. A value to be formatted and inserted into the string’s placeholder
  • Returns - A formatted string

Example:

strings.py
# format() method
string = 'Python Strings'
print('I love {}'.format(string))
print('I love {0}'.format(string))

Output

command
C:\Users\Your Name> python strings.py
I love Python Strings
I love Python Strings

The format_map() method formats the specified value(s) and insert them inside the string’s placeholder.

Syntax:

  • map - Required. A dictionary containing the variables to insert into the string’s placeholder
  • Returns - A formatted string

Example:

strings.py
# format_map() method
string = 'Python Strings'
print('I love {name}'.format_map({'name': string}))
print('I love {name}'.format_map({'name': 'Python'}))

Output

command
C:\Users\Your Name> python strings.py
I love Python Strings
I love Python

The index() method finds the first occurrence of the specified value. The index() method raises an exception if the value is not found.

Syntax:

  • value - Required. The value to search for
  • start (optional) - Optional. Where to start the search. Default is 0
  • end (optional) - Optional. Where to end the search. Default is len(string)
  • Returns - The index of the first occurrence of the specified value

Example:

strings.py
# index() method
string = 'Python Strings'
print(string.index('s'))
print(string.index('s', 7, 14))

Output

command
C:\Users\Your Name> python strings.py
7
Traceback (most recent call last):
  File "strings.py", line 4, in <module>
    print(string.index('s', 7, 14))
ValueError: substring not found

The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).

Syntax:

  • Returns - True if all characters in the string are alphanumeric

Example:

strings.py
# isalnum() method
string = 'PythonStrings'
print(string.isalnum())
print('Python Strings'.isalnum())

Output

command
C:\Users\Your Name> python strings.py
True
False

The isalpha() method returns True if all the characters are alphabet letters (a-z).

Syntax:

  • Returns - True if all characters in the string are alphabet letters

Example:

strings.py
# isalpha() method
string = 'PythonStrings'
print(string.isalpha())
print('Python Strings'.isalpha())

Output

command
C:\Users\Your Name> python strings.py
True
False

The isdecimal() method returns True if all the characters are decimals (0-9).

Syntax:

  • Returns - True if all characters in the string are decimals

Example:

strings.py
# isdecimal() method
string = '123456'
print(string.isdecimal())
print('123 456'.isdecimal())

Output

command
C:\Users\Your Name> python strings.py
True
False

The isdigit() method returns True if all the characters are digits, otherwise False.

Syntax:

  • Returns - True if all characters in the string are digits

Example:

strings.py
# isdigit() method
string = '123456'
print(string.isdigit())
print('123 456'.isdigit())

Output

command
C:\Users\Your Name> python strings.py
True
False

The isidentifier() method returns True if the string is a valid identifier, otherwise False.

Syntax:

  • Returns - True if the string is a valid identifier, otherwise False

Example:

strings.py
# isidentifier() method
string = 'PythonStrings'
print(string.isidentifier())
print('Python Strings'.isidentifier())
print('Python-Strings'.isidentifier())
print('Python_Strings'.isidentifier())

Output

command
C:\Users\Your Name> python strings.py
True
False
False
True

The islower() method returns True if all the characters are in lower case, otherwise False.

Syntax:

  • Returns - True if all characters in the string are lower case

Example:

strings.py
# islower() method
string = 'python strings'
print(string.islower())
print('Python Strings'.islower())

Output

command
C:\Users\Your Name> python strings.py
True
False

The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.

Syntax:

  • Returns - True if all characters in the string are numeric

Example:

strings.py
# isnumeric() method
string = '123456'
print(string.isnumeric())
print('123 456'.isnumeric())

Output

command
C:\Users\Your Name> python strings.py
True
False

The isprintable() method returns True if all the characters are printable, otherwise False.

Syntax:

  • Returns - True if all characters in the string are printable

Example:

strings.py
# isprintable() method
string = 'Python Strings'
print(string.isprintable())
print('Python\nStrings'.isprintable())

Output

command
C:\Users\Your Name> python strings.py
True
False

The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.

Syntax:

  • Returns - True if all characters in the string are whitespaces

Example:

strings.py
# isspace() method
string = '   '
print(string.isspace())
print('Python Strings'.isspace())

Output

command
C:\Users\Your Name> python strings.py
True
False

The istitle() method returns True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters, otherwise False.

Syntax:

  • Returns - True if all words in a text start with a upper case letter, AND the rest of the word are lower case letters

Example:

strings.py
# istitle() method
string = 'Python Strings'
print(string.istitle())
print('Python strings'.istitle())

Output

command
C:\Users\Your Name> python strings.py
True
False

The isupper() method returns True if all the characters are in upper case, otherwise False.

Syntax:

  • Returns - True if all characters in the string are upper case

Example:

strings.py
# isupper() method
string = 'PYTHON STRINGS'
print(string.isupper())
print('Python Strings'.isupper())

Output

command
C:\Users\Your Name> python strings.py
True
False

The join() method takes all items in an iterable and joins them into one string.

Syntax:

  • iterable - Required. Any iterable object where all the returned values are strings

Example:

strings.py
# join() method
string = 'Python Strings'
print(' '.join(string))
print(''.join(string))

Output

command
C:\Users\Your Name> python strings.py
P y t h o n   S t r i n g s
Python Strings

The ljust() method will left align the string, using a specified character (space is default) as the fill character.

Syntax:

  • length - The length of the returned string
  • character (optional) - The character to fill the missing space on the right side. Default is " "
  • Returns - A left aligned string

Example:

strings.py
# ljust() method
string = 'Python Strings'
print(string.ljust(20))
print(string.ljust(20, '*'))

Output

command
C:\Users\Your Name> python strings.py
Python Strings
Python Strings*******

The lower() method returns a string where all characters are lower case.

Syntax:

  • Returns - A lower case string

Example:

strings.py
# lower() method
string = 'Python Strings'
print(string.lower())

Output

command
C:\Users\Your Name> python strings.py
python strings

The lstrip() method removes any leading characters (space is the default leading character to remove)

Syntax:

  • characters (optional) - A set of characters to remove as leading characters
  • Returns - A left trim version of the string

Example:

strings.py
# lstrip() method
string = '   Python Strings'
print(string.lstrip())
print(string.lstrip('   '))

Output

command
C:\Users\Your Name> python strings.py
Python Strings
Python Strings

The maketrans() method generates a translation table that can be used for replacing specified characters. This method is often used in conjunction with the translate() method to perform character substitutions in a string.

Syntax:

  • x - If only one argument is provided, it should be a dictionary mapping Unicode ordinals to translation strings. If two arguments are provided, they must be of equal length, and each character in x will be mapped to the character at the same position in y. If three arguments are provided, each charac ter in x will be mapped to the character at the same position in y and z.
  • y - Mapping table, where each character in x will be mapped to the character at the same position in y. This argument is optional.
  • z - If present, it specifies a string to be used for deleting characters.

Returns:

  • A translation table.

Example:

strings.py
# maketrans() method
intab = "aeiou"
outtab = "12345"
trans_table = str.maketrans(intab, outtab)
 
string = "Hello, World!"
translated_string = string.translate(trans_table)
 
print("Original String:", string)
print("Translated String:", translated_string)

Output

command
C:\Users\Your Name> python strings.py
Original String: Hello, World!
Translated String: H2ll4, W4rld!

The partition() method divides a string into three parts based on the specified separator. It searches for the separator in the string, and once found, it returns a tuple containing the part before the separator, the separator itself, and the part after the separator.

Syntax:

  • separator - The string to search for within the given string.

Returns:

  • A tuple containing three elements: the part before the separator, the separator itself, and the part after the separator.

Example:

strings.py
# partition() method
string = "Python is fun"
partitioned = string.partition("is")
 
print("Original String:", string)
print("Partitioned Result:", partitioned)

Output

command
C:\Users\Your Name> python strings.py
Original String: Python is fun
Partitioned Result: ('Python ', 'is', ' fun')

The replace() method returns a copy of the string where all occurrences of a substring is replaced with another substring.

Syntax:

  • old - The substring to be replaced.
  • new - The string which would replace the substring passed.
  • count (optional) - The number of times old substring needs to be replaced with new substring. Default is -1 which means replace all occurrences.
  • Returns - A copy of the string where all occurrences of a substring is replaced with another substring.

Example:

strings.py
# replace() method
string = "Python is fun"
replaced = string.replace("is", "was")
print("Original String:", string)
print("Replaced String:", replaced)

Output

command
C:\Users\Your Name> python strings.py
Original String: Python is fun
Replaced String: Python was fun

The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found.

Syntax:

  • value - Required. The value to search for
  • start (optional) - Optional. Where to start the search. Default is 0
  • end (optional) - Optional. Where to end the search. Default is len(string)
  • Returns - The index of the last occurrence of the specified value

Example:

strings.py
# rfind() method
string = 'Python Strings'
print(string.rfind('s'))
print(string.rfind('s', 7, 14))

Output

command
C:\Users\Your Name> python strings.py
13
-1

The rindex() method finds the last occurrence of the specified value. The rindex() method raises an exception if the value is not found.

Syntax:

  • value - Required. The value to search for
  • start (optional) - Optional. Where to start the search. Default is 0
  • end (optional) - Optional. Where to end the search. Default is len(string)
  • Returns - The index of the last occurrence of the specified value

Example:

strings.py
# rindex() method
string = 'Python Strings'
print(string.rindex('s'))
print(string.rindex('s', 7, 14))

Output

command
C:\Users\Your Name> python strings.py
13
Traceback (most recent call last):
  File "strings.py", line 4, in <module>
    print(string.rindex('s', 7, 14))
ValueError: substring not found

The rjust() method will right align the string, using a specified character (space is default) as the fill character.

Syntax:

  • length - The length of the returned string
  • character (optional) - The character to fill the missing space on the left side. Default is " "
  • Returns - A right aligned string

Example:

strings.py
# rjust() method
string = 'Python Strings'
print(string.rjust(20))
print(string.rjust(20, '*'))

Output

command
C:\Users\Your Name> python strings.py
      Python Strings
*******Python Strings

The rpartition() method divides a string into three parts based on the specified separator. It searches for the separator in the string, moving from right to left, and once found, it returns a tuple containing the part before the separator, the separator itself, and the part after the separator.

Syntax:

  • separator - The string to search for within the given string.
  • Returns - A tuple containing three elements: the part before the separator, the separator itself, and the part after the separator.

Example:

strings.py
# rpartition() method
string = "Python is fun"
partitioned = string.rpartition("is")
print("Original String:", string)
print("Partitioned Result:", partitioned)

Output

command
C:\Users\Your Name> python strings.py
Original String: Python is fun
Partitioned Result: ('Python ', 'is', ' fun')

The rsplit() method splits a string into a list, starting from the right. If no “max” is specified, this method will return the same as the split() method.

Syntax:

  • separator (optional) - Specifies the separator to use when splitting the string. By default any whitespace is a separator
  • maxsplit (optional) - Specifies how many splits to do. Default value is -1, which is “all occurrences”
  • Returns - A list of strings split at each separator

Example:

strings.py
# rsplit() method
string = 'Python Strings'
print(string.rsplit())
print(string.rsplit(' ', 1))

Output

command
C:\Users\Your Name> python strings.py
['Python', 'Strings']
['Python', 'Strings']

The rstrip() method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.

Syntax:

  • characters (optional) - A set of characters to remove as trailing characters
  • Returns - A right trim version of the string

Example:

strings.py
# rstrip() method
string = 'Python Strings   '
print(string.rstrip())
print(string.rstrip('   '))

Output

command
C:\Users\Your Name> python strings.py
Python Strings
Python Strings

The split() method splits a string into a list.

Syntax:

  • separator (optional) - Specifies the separator to use when splitting the string. By default any whitespace is a separator
  • maxsplit (optional) - Specifies how many splits to do. Default value is -1, which is “all occurrences”
  • Returns - A list of strings split at each separator

Example:

strings.py
# split() method
string = 'Python Strings'
print(string.split())
print(string.split(' ', 1))

Output

command
C:\Users\Your Name> python strings.py
['Python', 'Strings']
['Python', 'Strings']

The splitlines() method splits a string into a list. The splitting is done at line breaks.

Syntax:

  • keepends (optional) - Specifies if the line breaks should be included (True), or not (False). Default value is False
  • Returns - A list of lines in the string

Example:

strings.py
# splitlines() method
string = 'Python\nStrings'
print(string.splitlines())
print(string.splitlines(True))

Output

command
C:\Users\Your Name> python strings.py
['Python', 'Strings']
['Python\n', 'Strings']

The startswith() method returns True if the string starts with the specified value, otherwise False.

Syntax:

  • value - Required. The value to check if the string starts with
  • start (optional) - Optional. An Integer specifying at which position to start the search
  • end (optional) - Optional. An Integer specifying at which position to end the search
  • Returns - True if the string starts with the specified value, otherwise False

Example:

strings.py
# startswith() method
string = 'Python Strings'
print(string.startswith('P'))
print(string.startswith('p', 7, 14))

Output

command
C:\Users\Your Name> python strings.py
True
False

The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to remove)

Syntax:

  • characters (optional) - A set of characters to remove as leading/trailing characters
  • Returns - A trimmed version of the string

Example:

strings.py
# strip() method
string = '   Python Strings   '
print(string.strip())
print(string.strip('   '))

Output

command
C:\Users\Your Name> python strings.py
Python Strings
Python Strings

The swapcase() method returns a string where all the upper case letters are lower case and vice versa.

Syntax:

  • Returns - A string where all the upper case letters are lower case and vice versa

Example:

strings.py
# swapcase() method
string = 'Python Strings'
print(string.swapcase())

Output

command
C:\Users\Your Name> python strings.py
pYTHON sTRINGS

The title() method returns a string where the first character in every word is upper case. Like a header, or a title.

Syntax:

  • Returns - A string where the first character in every word is upper case

Example:

strings.py
# title() method
string = 'Python Strings'
print(string.title())

Output

command
C:\Users\Your Name> python strings.py
Python Strings

The translate() method returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table.

Syntax:

  • table - A mapping table, where each character in the intab parameter will be mapped to the character at the same position in the outtab parameter.
  • Returns - A string where specified characters are replaced with specified characters

Example:

strings.py
# translate() method
string = 'Python Strings'
print(string.translate({ord('P'): 'J'}))
print(string.translate({ord('P'): 'J', ord('S'): 'L'}))

Output

command
C:\Users\Your Name> python strings.py
Jython Strings
Jython Ltrings

The upper() method returns a string where all characters are in upper case.

Syntax:

  • Returns - A string where all characters are in upper case
  • Example:
strings.py
# upper() method
string = 'Python Strings'
print(string.upper())

Output

command
C:\Users\Your Name> python strings.py
PYTHON STRINGS

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length.

Syntax:

  • length - The length of the returned string, with 0 digits filled to the left
  • Returns - A copy of the string with 0 digits to the left of the specified length

Example:

strings.py
# zfill() method
string = 'Python Strings'
print(string.zfill(20))
print(string.zfill(20).upper())

Output

command
C:\Users\Your Name> python strings.py
000000Python Strings
000000PYTHON STRINGS

The + operator is used to concatenate two strings.

Syntax:

  • string1 - Required. First string to be concatenated
  • string2 - Required. Second string to be concatenated
  • Returns - A concatenated string

Example:

strings.py
# + operator
string1 = 'Python'
string2 = 'Strings'
print(string1 + string2)

Output

command
C:\Users\Your Name> python strings.py
PythonStrings

The * operator is used to repeat a string for a given number of times.

Syntax:

  • string - Required. The string to be repeated
  • number - Required. A number specifying how many times the string should be repeated
  • Returns - A string repeated the specified number of times

Example:

strings.py
# * operator
string = 'Python Strings'
print(string * 2)
print(string * 3)

Output

command
C:\Users\Your Name> python strings.py
Python StringsPython Strings
Python StringsPython StringsPython Strings

The [] operator is used to slice a string.

Syntax:

  • index - Required. An integer specifying at which position to start the slicing. The indexing starts from 0
  • Returns - A sliced string

Example:

strings.py
# [] operator
string = 'Python Strings'
print(string[0])
print(string[7])

Output

command
C:\Users\Your Name> python strings.py
P
S

The [:] operator is used to slice a string.

Syntax:

  • start (optional) - Optional. An integer specifying at which position to start the slicing. The indexing starts from 0
  • end (optional) - Optional. An integer specifying at which position to end the slicing
  • step (optional) - Optional. An integer specifying the step of the slicing. Default is 1
  • Returns - A sliced string

Example:

strings.py
# [:] operator
string = 'Python Strings'
print(string[:6])
print(string[7:])

Output

command
C:\Users\Your Name> python strings.py
Python
Strings

The in operator returns True if a specified character is present in the string.

Syntax:

  • character - Required. A character to be searched for
  • string - Required. The string to search in
  • Returns - True if the specified character is present in the string

Example:

strings.py
# in operator
string = 'Python Strings'
print('P' in string)
print('p' in string)

Output

command
C:\Users\Your Name> python strings.py
True
False

The not in operator returns True if a specified character is not present in the string.

Syntax:

  • character - Required. A character to be searched for
  • string - Required. The string to search in
  • Returns - True if the specified character is not present in the string

Example:

strings.py
# not in operator
string = 'Python Strings'
print('P' not in string)
print('p' not in string)

Output

command
C:\Users\Your Name> python strings.py
False
True

The % operator is used to format a set of variables enclosed in a “tuple” (a fixed size list), together with a format string, which contains normal text together with “argument specifiers”, special symbols like %s and %d.

Syntax:

  • string - Required. A string containing the format string and argument specifiers
  • values - Required. A tuple containing the values to be formatted
  • Returns - A formatted string

Example:

strings.py
# % operator
string = 'Python %s'
print(string % 'Strings')
print(string % 3.6)

Output

command
C:\Users\Your Name> python strings.py
Python Strings
Python 3.6

The < operator is used to compare two strings, to determine if the left string is less than the right string.

Syntax:

  • string1 - Required. The first string to be compared
  • string2 - Required. The second string to be compared
  • Returns - True if the left string is less than the right string

Example:

strings.py
# < operator
string1 = 'Python'
string2 = 'Strings'
print(string1 < string2)
print(string1 < 'Python')

Output

command
C:\Users\Your Name> python strings.py
True
False

The <= operator is used to compare two strings, to determine if the left string is less than or equal to the right string.

Syntax:

  • string1 - Required. The first string to be compared
  • string2 - Required. The second string to be compared
  • Returns - True if the left string is less than or equal to the right string

Example:

strings.py
# <= operator
string1 = 'Python'
string2 = 'Strings'
print(string1 <= string2)
print(string1 <= 'Python')

Output

command
C:\Users\Your Name> python strings.py
True
True

The > operator is used to compare two strings, to determine if the left string is greater than the right string.

Syntax:

  • string1 - Required. The first string to be compared
  • string2 - Required. The second string to be compared
  • Returns - True if the left string is greater than the right string

Example:

strings.py
# > operator
string1 = 'Python'
string2 = 'Strings'
print(string1 > string2)
print(string1 > 'Python')

Output

command
C:\Users\Your Name> python strings.py
False
False

The >= operator is used to compare two strings, to determine if the left string is greater than or equal to the right string.

Syntax:

  • string1 - Required. The first string to be compared
  • string2 - Required. The second string to be compared
  • Returns - True if the left string is greater than or equal to the right string

Example:

strings.py
# >= operator
string1 = 'Python'
string2 = 'Strings'
print(string1 >= string2)
print(string1 >= 'Python')

Output

command
C:\Users\Your Name> python strings.py
False
True

The == operator is used to compare two strings, to determine if the left string is equal to the right string.

Syntax:

  • string1 - Required. The first string to be compared
  • string2 - Required. The second string to be compared
  • Returns - True if the left string is equal to the right string

Example:

strings.py
# == operator
string1 = 'Python'
string2 = 'Strings'
print(string1 == string2)
print(string1 == 'Python')

Output

command
C:\Users\Your Name> python strings.py
False
True

The != operator is used to compare two strings, to determine if the left string is not equal to the right string.

Syntax:

  • string1 - Required. The first string to be compared
  • string2 - Required. The second string to be compared
  • Returns - True if the left string is not equal to the right string

Example:

strings.py
# != operator
string1 = 'Python'
string2 = 'Strings'
print(string1 != string2)
print(string1 != 'Python')

Output

command
C:\Users\Your Name> python strings.py
True
False

The ord() function returns an integer representing the Unicode character.

Syntax:

  • character - Required. A character
  • Returns - An integer representing the Unicode character

Example:

strings.py
# ord() function
print(ord('A'))
print(ord('a'))

Output

command
C:\Users\Your Name> python strings.py
65
97

The hex() function converts an integer number to the corresponding hexadecimal string.

Syntax:

  • number - Required. An integer number (int object)
  • Returns - A hexadecimal string

Example:

strings.py
# hex() function
print(hex(255))
print(hex(-42))

Output

command
C:\Users\Your Name> python strings.py
0xff
-0x2a

The oct() function converts an integer number to the corresponding octal string.

Syntax:

  • number - Required. An integer number (int object)
  • Returns - An octal string

Example:

strings.py
# oct() function
print(oct(255))
print(oct(-42))

Output

command
C:\Users\Your Name> python strings.py
0o377
-0o52

The bin() function converts an integer number to the corresponding binary string.

Syntax:

  • number - Required. An integer number (int object)
  • Returns - A binary string

Example:

strings.py
# bin() function
print(bin(255))
print(bin(-42))

Output

command
C:\Users\Your Name> python strings.py
0b11111111
-0b101010

The chr() function returns a character (a string) from an integer (represents unicode code point of the character).

Syntax:

  • number - Required. An integer representing the Unicode code point of the character
  • Returns - A character (a string) from an integer (represents unicode code point of the character)

Example:

strings.py
# chr() function
print(chr(65))
print(chr(97))

Output

command
C:\Users\Your Name> python strings.py
A
a

The len() function returns the number of items (length) in an object.

Syntax:

  • object - Required. An object (string, bytes or array etc.)
  • Returns - The number of items in an object

Example:

strings.py
# len() function
print(len('Python'))
print(len('Python Strings'))

Output

command
C:\Users\Your Name> python strings.py
6
14

The repr() function returns a printable representation of the given object.

Syntax:

  • object - Required. Any object, like lists, tuples, strings etc.
  • Returns - A printable representation of the given object

Example:

strings.py
# repr() function
print(repr('Python'))
print(repr('Python Strings'))

Output

command
C:\Users\Your Name> python strings.py
'Python'
'Python Strings'

The ascii() function returns a readable version of any object (Strings, Tuples, Lists, etc).

Syntax:

  • object - Required. Any object, like lists, tuples, strings etc.
  • Returns - A readable version of any object (Strings, Tuples, Lists, etc)

Example:

strings.py
# ascii() function
print(ascii('Python'))
print(ascii('Python Strings'))

Output

command
C:\Users\Your Name> python strings.py
'Python'
'Python Strings'

The max() function returns the largest item in an iterable.

Syntax:

  • iterable - Required. An iterable object (list, tuple, string etc.)
  • Returns - The largest item in the given iterable

Example:

strings.py
# max() function
print(max('Python'))
print(max('Python Strings'))

Output

command
C:\Users\Your Name> python strings.py
y
y

The min() function returns the smallest item in an iterable.

Syntax:

  • iterable - Required. An iterable object (list, tuple, string etc.)
  • Returns - The smallest item in the given iterable

Example:

strings.py
# min() function
print(min('Python'))
print(min('Python Strings'))

Output

command
C:\Users\Your Name> python strings.py
P
P

The str() function returns the string version of the given object.

Syntax:

  • object - Required. An object to be converted to string
  • Returns - The string version of the given object

Example:

strings.py
# str() function
print(str(3.6))
print(str(3.6) + ' is a float number')

Output

command
C:\Users\Your Name> python strings.py
3.6
3.6 is a float number

The type() function returns the type of the specified object.

Syntax:

  • object - Required. An object whose type needs to be returned
  • Returns - The type of the specified object

Example:

strings.py
# type() function
print(type('Python'))
print(type(3.6))

Output

command
C:\Users\Your Name> python strings.py
<class 'str'>
<class 'float'>

The help() function is used to display the documentation of modules, functions, classes, keywords etc.

Syntax:

  • object - Required. The object to be described
  • Returns - The documentation of the specified object

Example:

strings.py
# help() function
print(help(str.upper))

Output

command
C:\Users\Your Name> python strings.py
Help on method_descriptor:
 
upper(self, /)
    Return a copy of the string converted to uppercase.
 
None

In this tutorial, we have learned about the Python string methods and operators with the help of examples. We have also learned about the built-in functions that can be used with strings. Now you can use these methods and operators to manipulate strings in your Python programs.


sketch strip eating a string one character at a time p5.js
The argument is a set of characters, and strip removes them from each end repeatedly until it meets one that is not in the set. Watch it chew past the part you meant to remove. Every result shown was run: moocow.com becomes w, and the canonical example example.com gives the right answer for the wrong reason.
pch.quizTag pch.quizDefaultTitle
  1. What does `'moocow.com'.strip('.com')` return?

    pch.quizShowAnswer

    C — `'w'` — Verified. The argument is a character SET — any of `.`, `c`, `o`, `m` — stripped from both ends repeatedly. It eats through `moocow` until it reaches `w`.

  2. Why does `'example.com'.strip('.com')` make the bug hard to spot?

    pch.quizShowAnswer

    B — It returns `'example'`, which is the answer you wanted — The canonical example gives the right answer for the wrong reason, so the code passes review and testing, then mangles different data later.

  3. Which call removes exactly the text `.com` from the end, once, if present?

    pch.quizShowAnswer

    C — `s.removesuffix('.com')` — `removesuffix` (3.9+) is a literal, single, anchored removal. `replace` would also strip it from the middle of the string.

  4. `''.split()` and `''.split(',')` — what do they return?

    pch.quizShowAnswer

    C — `[]` and `['']` — Verified. That asymmetry is why a loop over `line.split(',')` runs once on a blank line with an empty field, so blank lines silently become rows of empty values.

Exercise 3 – startswith() and endswith()

Section titled “Exercise 3 – startswith() and endswith()”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading