Python String
Python String

Python String

In python, the string is a sequential collection of characters, and it is an object of python’s built-in class ‘str’. In python, the strings are represented by enclosing the string characters using quotes, i.e., either a single quote ('), double quote ("), or triple quote (''' or """) as long as the starting and ending of the quotes are same.

Following is the example of creating the strings in python using different quotes.

a = 'Hi'
b = "Welcome to Tutlane"
c = '''Learn Python'''
d = """Best Learning Resource"""
print(a)
print(b)
print(c)
print(d)
print(type(a))
print(type(b))
print(type(c))
print(type(d))

If you observe the above example, we created different variables (abcd) by assigning the string types with different quotes. Here, we used print() function to print string values and the type() function to know the type of variables.

When you execute the above python example, you will get the result as shown below.

Hi
Welcome to Tutlane
Learn Python
Best Learning Resource
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

If you observe the above result, the type of variables (abcd) returned as str.

Multiline Strings

Access String Characters

String Slicing

Change or Remove String Characters

String Concatenation

String Length

Check If String Contains

Convert to String

Escape Characters

String Formatting

In python, the format() method is useful to format complex strings and numbers. The format strings will contain the curly braces { } and the format() method. We use those curly braces { } as placeholders to replace with the content of the parameters.

Following is the syntax of the format() method in python to format the strings.

string.format(arg1, arg2, etc.)

The python format() method will accept unlimited arguments and replace the curly brace { } placeholders with the content of the respective arguments.

Following is the example of formatting the strings using the format() method in python.

str1 = "{} to {}".format("Welcome", "Tutlane.com")

print(str1)
Welcome to Tutlane.com
name = "Suresh"
age = 33

str2 = "My name is {}, and I am {} years old"

print(str2.format(name, age))
My name is Suresh, and I am 33 years old

If you observe the above result, we created strings with placeholders without specifying any order, and we are not sure whether the arguments are placed in the correct order or not.

To make sure the arguments are placed in the correct order, you can define the positional or keyword arguments in the placeholders like as shown below.

# Positional arguments
str1 = "{1} to {0}".format("Tutlane.com", "Welcome")
print(str1)
# Keyword arguments
name = "Suresh"
age = 33
str2 = "My name is {x}, and I am {y} years old"
print(str2.format(y = age, x = name))

If you observe the above example, we defined the placeholders with positional and keyword arguments to specify the order.

When you execute the above python program, you will get the result as shown below.

Welcome to Tutlane.com
My name is Suresh, and I am 33 years old

Python String Methods

Method
Description
Example Usage
Output
capitalize()
Converts first character to uppercase
"hello".capitalize()
Hello
casefold()
Converts to lowercase (Unicode safe)
"HELLO".casefold()
hello
center()
Centers string in specified width
"hi".center(6)
' hi '
count()
Counts how many times a value appears
"hello".count("l")
2
encode()
Encodes string as bytes
"hello".encode()
b'hello'
endswith()
Checks if string ends with a value
"hello".endswith("o")
True
expandtabs()
Sets tab size
"a\tb".expandtabs(4)
'a b'
find()
Finds first occurrence index
"hello".find("l")
2
format()
Formats using placeholders
"{} {}".format("Hi", "there")
Hi there
format_map()
Formats using dictionary map
"{x}".format_map({"x": 5})
5
index()
Finds index or raises error if not found
"hello".index("e")
1
isalnum()
Checks if all characters are alphanumeric
"abc123".isalnum()
True
isalpha()
Checks if all characters are letters
"abc".isalpha()
True
isascii()
Checks if all characters are ASCII
"abc".isascii()
True
isdecimal()
Checks if all characters are decimals
"123".isdecimal()
True
isdigit()
Checks if all characters are digits
"123".isdigit()
True
isidentifier()
Checks if valid Python identifier
"name_1".isidentifier()
True
islower()
Checks if all characters are lowercase
"abc".islower()
True
isnumeric()
Checks if all characters are numeric
"123".isnumeric()
True
isprintable()
Checks if all characters are printable
"hello".isprintable()
True
isspace()
Checks if string is all whitespace
" ".isspace()
True
istitle()
Checks if title case
"Hello World".istitle()
True
isupper()
Checks if all characters are uppercase
"HELLO".isupper()
True
join()
Joins iterable into a string
" ".join(["Python", "3"])
Python 3
ljust()
Left-aligns in a field
"hi".ljust(4)
'hi '
lower()
Converts all characters to lowercase
"HELLO".lower()
hello
lstrip()
Removes leading spaces
" hi".lstrip()
'hi'
maketrans()
Creates a translation table
str.maketrans("a", "x")
{'a': 'x'}
partition()
Splits at first occurrence of separator
"a-b-c".partition("-")
('a', '-', 'b-c')
replace()
Replaces old with new
"hi".replace("i", "ello")
hello
rfind()
Finds last occurrence of value
"hello".rfind("l")
3
rindex()
Finds last index or errors
"hello".rindex("l")
3
rjust()
Right-aligns string
"hi".rjust(4)
' hi'
rpartition()
Splits at last occurrence of separator
"a-b-c".rpartition("-")
('a-b', '-', 'c')
rsplit()
Splits from right side
"a,b,c".rsplit(",", 1)
['a,b', 'c']
rstrip()
Removes trailing spaces
"hi ".rstrip()
'hi'
split()
Splits on separator
"a,b".split(",")
['a', 'b']
splitlines()
Splits at line breaks
"a\nb".splitlines()
['a', 'b']
startswith()
Checks if string starts with value
"hello".startswith("he")
True
strip()
Removes both leading and trailing spaces
" hi ".strip()
'hi'
swapcase()
Swaps letter case
"Hi".swapcase()
hI
title()
Converts to title case
"hello world".title()
Hello World
translate()
Applies translation table
"abc".translate(str.maketrans("a", "x"))
xbc
upper()
Converts all characters to uppercase
"hi".upper()
HI
zfill()
Pads with zeroes on the left
"42".zfill(5)
00042