Python - String Methods

String Methods

Python provides a set of built-in methods that can be applied to strings. It's important to note that all string methods return new values; they do not modify the original string.

Common String Methods

MethodDescriptionExample
capitalize()Converts the first character to uppercase.print("ashlya".capitalize()) ➔ Output: Ashlya
casefold()Converts the string to lowercase for case-insensitive comparisons.print("NEPAL".casefold()) ➔ Output: nepal
center()Returns a centered string with specified width.print("Nepal".center(10)) ➔ Output: Nepal
count()Returns the number of times a specified value occurs in the string.print("Pokhara is beautiful".count("a")) ➔ Output: 3
encode()Returns an encoded version of the string.print("Ashlya".encode()) ➔ Output: b'Ashlya'
endswith()Returns True if the string ends with the specified value.print("Everest".endswith("st")) ➔ Output: True
expandtabs()Sets the tab size of the string.print("Nepal\tis\tbeautiful.".expandtabs(4)) ➔ Output: Nepal is beautiful.
find()Searches for a specified value and returns its position.print("Kathmandu".find("ham")) ➔ Output: 3
format()Formats specified values in a string.print("Nepal is {}.".format("beautiful")) ➔ Output: Nepal is beautiful.
format_map()Similar to format(), but uses a mapping for substitution.print("I live in {city}.".format_map({"city": "Kathmandu"})) ➔ Output: I live in Kathmandu.
index()Searches for a specified value and returns its position.print("Bhaktapur".index("k")) ➔ Output: 2
isalnum()Returns True if all characters are alphanumeric.print("Ashlya2024".isalnum()) ➔ Output: True
isalpha()Returns True if all characters are alphabetic.print("Nepal".isalpha()) ➔ Output: True
isascii()Returns True if all characters are ASCII characters.print("Ashlya".isascii()) ➔ Output: True
isdecimal()Returns True if all characters are decimal digits.print("2024".isdecimal()) ➔ Output: True
isdigit()Returns True if all characters are digits.print("12345".isdigit()) ➔ Output: True
isidentifier()Returns True if the string is a valid identifier.print("ashlya_is_awesome".isidentifier()) ➔ Output: True
islower()Returns True if all characters are lowercase.print("ashlya".islower()) ➔ Output: True
isnumeric()Returns True if all characters are numeric.print("12345".isnumeric()) ➔ Output: True
isprintable()Returns True if all characters are printable.print("Nepal!".isprintable()) ➔ Output: True
isspace()Returns True if all characters are whitespace.print(" ".isspace()) ➔ Output: True
istitle()Returns True if the string follows the rules of a title.print("This Is A Title".istitle()) ➔ Output: True
isupper()Returns True if all characters are uppercase.print("NEPAL".isupper()) ➔ Output: True
join()Joins the elements of an iterable to the end of the string.print(", ".join(["Kathmandu", "Pokhara", "Bhaktapur"])) ➔ Output: Kathmandu, Pokhara, Bhaktapur
ljust()Returns a left-justified version of the string.print("Nepal".ljust(10)) ➔ Output: Nepal
lower()Converts a string to lowercase.print("Ashlya".lower()) ➔ Output: ashlya
lstrip()Returns a left trim version of the string.print(" Ashlya".lstrip()) ➔ Output: Ashlya
maketrans()Returns a translation table to be used in translations.trans = str.maketrans("a", "o"); print("Nepal".translate(trans)) ➔ Output: NePol
partition()Returns a tuple where the string is parted into three parts.print("Hello, Nepal!".partition(",")) ➔ Output: ('Hello', ',', ' Nepal!')
replace()Replaces a specified value with another value.print("Nepal is great".replace("great", "amazing")) ➔ Output: Nepal is amazing
rfind()Searches for a specified value and returns the last position of where it was found.print("Nepal, India, China, Nepal".rfind("Nepal")) ➔ Output: 18
rindex()Searches for a specified value and returns the last position of where it was found.print("Nepal, India, China, Nepal".rindex("Nepal")) ➔ Output: 18
rjust()Returns a right-justified version of the string.print("Nepal".rjust(10)) ➔ Output: Nepal
rpartition()Returns a tuple where the string is parted into three parts from the right.print("Nepal, India, China".rpartition(",")) ➔ Output: ('Nepal', ',', ' India, China')
rsplit()Splits the string at the specified separator and returns a list.print("Nepal, India, China".rsplit(", ")) ➔ Output: ['Nepal', 'India', 'China']
rstrip()Returns a right trim version of the string.print("Ashlya ".rstrip()) ➔ Output: Ashlya
split()Splits the string at the specified separator and returns a list.print("Nepal, India, China".split(", ")) ➔ Output: ['Nepal', 'India', 'China']
splitlines()Splits the string at line breaks and returns a list.print("Line 1\nLine 2\nLine 3".splitlines()) ➔ Output: ['Line 1', 'Line 2', 'Line 3']
startswith()Returns True if the string starts with the specified value.print("Everest".startswith("E")) ➔ Output: True
strip()Returns a trimmed version of the string (removes spaces).print(" Ashlya ".strip()) ➔ Output: Ashlya
swapcase()Swaps cases, lower case becomes upper case and vice versa.print("Ashlya".swapcase()) ➔ Output: aSHLYA
title()Converts the first character of each word to uppercase.print("nepal is beautiful".title()) ➔ Output: Nepal Is Beautiful
translate()Returns a translated string based on a translation table.trans = str.maketrans("aeiou", "12345"); print("Nepal".translate(trans)) ➔ Output: N2p1l
upper()Converts a string to uppercase.print("ashlya".upper()) ➔ Output: ASHLYA
zfill()Fills the string with a specified number of leading zeros.print("42".zfill(5)) ➔ Output: 00042

Common String Methods

capitalize()

Converts the first character to uppercase.

print("ashlya".capitalize())  # Output: Ashlya

casefold()

Converts the string to lowercase for case-insensitive comparisons.

print("NEPAL".casefold())  # Output: nepal

center()

Returns a centered string with specified width.

print("Nepal".center(10))  # Output:   Nepal   

count()

Returns the number of times a specified value occurs in the string.

print("Pokhara is beautiful".count("a"))  # Output: 3

encode()

Returns an encoded version of the string.

print("Ashlya".encode())  # Output: b'Ashlya'

endswith()

Returns True if the string ends with the specified value.

print("Everest".endswith("st"))  # Output: True

expandtabs()

Sets the tab size of the string.


print("Nepal\tis\tbeautiful.".expandtabs(4))  # Output: Nepal    is    beautiful.

find()

Searches for a specified value and returns its position.


print("Kathmandu".find("ham"))  # Output: 3

format()

Formats specified values in a string.


print("Nepal is {}.".format("beautiful"))  # Output: Nepal is beautiful.

format_map()

Similar to format(), but uses a mapping for substitution.

print("I live in {city}.".format_map({"city": "Kathmandu"}))  # Output: I live in Kathmandu.

index()

Searches for a specified value and returns its position.


print("Bhaktapur".index("k"))  # Output: 2

isalnum()

Returns True if all characters are alphanumeric.


print("Ashlya2024".isalnum())  # Output: True

isalpha()

Returns True if all characters are alphabetic.


print("Nepal".isalpha())  # Output: True

isascii()

Returns True if all characters are ASCII characters.

print("Ashlya".isascii())  # Output: True

isdecimal()

Returns True if all characters are decimal digits.


print("2024".isdecimal())  # Output: True

isdigit()

Returns True if all characters are digits.


print("12345".isdigit())  # Output: True

isidentifier()

Returns True if the string is a valid identifier.

print("ashlya_is_awesome".isidentifier())  # Output: True

islower()

Returns True if all characters are lowercase.


print("ashlya".islower())  # Output: True

isnumeric()

Returns True if all characters are numeric.

print("12345".isnumeric())  # Output: True

isprintable()

Returns True if all characters are printable.


print("Nepal!".isprintable())  # Output: True

isspace()

Returns True if all characters are whitespace.

print("   ".isspace())  # Output: True

istitle()

Returns True if the string follows the rules of a title.

print("This Is A Title".istitle())  # Output: True

isupper()

Returns True if all characters are uppercase.

print("NEPAL".isupper())  # Output: True

join()

Joins the elements of an iterable to the end of the string.


print(", ".join(["Kathmandu", "Pokhara", "Bhaktapur"]))  # Output: Kathmandu, Pokhara, Bhaktapur

ljust()

Returns a left-justified version of the string.


print("Nepal".ljust(10))  # Output: Nepal

lower()

Converts a string to lowercase.

print("Ashlya".lower())  # Output: ashlya

lstrip()

Returns a left trim version of the string.

print("   Ashlya".lstrip())  # Output: Ashlya

maketrans()

Returns a translation table to be used in translations.


trans = str.maketrans("a", "o")
print("Nepal".translate(trans))  # Output: NePol

partition()

Returns a tuple where the string is parted into three parts.

print("Hello, Nepal!".partition(","))  # Output: ('Hello', ',', ' Nepal!')

replace()

Replaces a specified value with another value.

print("Nepal is great".replace("great", "amazing"))  # Output: Nepal is amazing

rfind()

Searches for a specified value and returns the last position of where it was found.

print("Nepal, India, China, Nepal".rfind("Nepal"))  # Output: 18

rindex()

Searches for a specified value and returns the last position of where it was found.

print("Nepal, India, China, Nepal".rindex("Nepal"))  # Output: 18

rjust()

Returns a right-justified version of the string.

print("Nepal".rjust(10))  # Output:      Nepal

rpartition()

Returns a tuple where the string is parted into three parts from the right.

print("Nepal, India, China".rpartition(","))  # Output: ('Nepal', ',', ' India, China')

rsplit()

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


print("Nepal, India, China".rsplit(", "))  # Output: ['Nepal', 'India', 'China']

rstrip()

Returns a right trim version of the string.


print("Ashlya   ".rstrip())  # Output: Ashlya

split()

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

print("Nepal, India, China".split(", "))  # Output: ['Nepal', 'India', 'China']