A string is a sequence of characters enclosed between single or double quotation marks. Strings are one of the most common data types in Python and can contain letters, numbers, symbols, or even spaces.
Creating Strings
name = "John Doe"
print(name)
message = "Hello, World!"
print(message)
If you want to print a statement with quotation marks in between the strings. Then you can use single quotes for convenience. For example:
print('He said, "I love Python programming"!')
Multiline Strings
You can create multiline strings by using triple single or triple double quotes. For example:
string = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(string)
string1 = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(string1)
Accessing Characters in a String
String is like an array of characters in python. You can access characters of string by using its index which starts from 0.
message = "Hello, World!"
print(message[0]) #output: H
print(message[1]) #output: e
print(message[5]) #output: ,
Length of a String
You can use the len()
function to find the length of a string.
message = "Hello, World!"
messageLength = len(message)
print(messageLength) #Output: 13
String Slicing
String is like an array of characters, so you can extract a part of a string using slicing.
message = "Hello, World!"
# Extract characters from index 0 to index 5 (including 0 but not 5)
print(message[0:5]) # Output: "Hello"
# Omitting start index (defaults to 0) (including 0 but not 5)
print(message[:5]) # Output: "Hello"
# Extract characters from index 3 to the end
print(message[3:]) # Output: "lo, World!"
# Slicing using negative index
print(message[0:-3]) # Output: "Hello, Wor"
# Python interprets above code as print(message[0:len(message)-3])
print(message[-1:]) # Output: "!"
# Python interprets above code as print(message[len(message)-1:])
Looping Through a String
Strings are iterable, so you can loop through each character in the string.
message = "Hello, World!"
for i in message:
print(i)
String Methods
Python provides several built-in methods for working with strings:
-
upper()
: Theupper()
method converts a string to upper case.message = "Hello, World!" print(message.upper()) #Output: HELLO, WORLD!
-
lower()
: Thelower()
method converts a string to lower case.message = "Hello, World!" print(message.lower()) #Output: hello, world!
-
capitalize()
: Thecapitalize()
method converts the first character of the string to uppercase and the rest other characters of the string to lowercase.message = "hello, World!" print(message.capitalize()) #Output: Hello, world!
-
split()
: Thesplit()
method splits the given string and returns the separated strings as list items.message = "Hello, World!" print(message.split(" ")) #Output: ['Hello,', 'World!']
-
strip()
: Thestrip()
method removes white spaces at the beginning and end of the string.message = " Hello, World! " print(message.strip()) #Output: Hello, World!
-
rstrip()
: Therstrip()
removes any trailing characters.message = " Hello, World! " print(message.rstrip("!")) #Output: Hello, World
-
replace()
: Thereplace()
method replaces all occurrences of a string with another string.message = "Hello, World!" print(message.replace("Hello", "Hi")) #Output: Hi, World!
-
center()
: Thecenter()
method aligns the string to the center as per the parameters given by the user.message = "Hello, World!" print(message.center(50)) # Output: " Hello, World! "
You can also provide padding character.
message = "Hello, World!" print(message.center(50,"!")) #Output:!!!!!!!!!!!!!!!!!!Hello, World!!!!!!!!!!!!!!!!!!!!
-
count()
: Thecount()
method returns the number of times the given value has occurred within the given string.message = "Hello, World!" print(message.count("l")) #Output: 3
-
title()
: Thetitle()
method capitalizes first letter of each word within the string.message = "Python is a programming language" print(message.title()) #Output: Python Is A Programming Language
-
startswith()
: Thestartswith()
method checks if the string starts with a given value. It gives result intrue
orfalse
.message = "Hello, World!" print(message.startswith("Hello")) #Output: True
-
endswith()
: Theendswith()
method checks if the string ends with a given value. It gives result intrue
orfalse
.message = "Hello, World!" print(message.endswith("!")) #Output: True
-
find()
: Thefind()
method searches for the first occurrence of the given value and returns the index where it is present. If given value is absent from the string then return-1
.message = "Hello, World!" print(message.find("W")) #Output: 7 print(message.find("a")) #Output: -1
-
index()
: Theindex()
method searches for the first occurrence of the given value and returns the index where it is present. If given value is absent from the string then raise an exception.message = "Hello, World!" print(message.index("W")) #Output: 7 print(message.index("a")) #Output: ValueError: substring not found
This method is somewhat similar to the
find()
method. The major difference being thatindex()
raises an exception if value is absent whereasfind()
return -1. -
isalnum()
: Theisalnum()
method returnsTrue
if the string consists only of A-Z, a-z, 0-9. If any other characters or punctuations are present, then it returnsFalse
.message = "Hello, World!" print(message.isalnum()) #Output: False message2 = "HelloWorld" print(message2.isalnum()) #Output: True
-
isalpha()
: Theisalpha()
method returnsTrue
if the string consists only of A-Z, a-z. If any other characters or punctuations or numbers(0-9) are present, then it returnsFalse
.message = "Hello, World!" print(message.isalpha()) #Output: False message2 = "HelloWorld" print(message2.isalpha()) #Output: True
-
isupper()
: Theisupper()
method returnsTrue
if all the characters in the string are upper case, else it returnsFalse.
message = "Hello, World!" print(message.isupper()) #Output: False
-
islower()
: Theislower()
method returnsTrue
if all the characters in the string are lower case, else it returnsFalse
.message = "hello, world!" print(message.islower()) #Output: True
-
isprintable()
: Theisprintable()
method returnsTrue
if all the values within the given string are printable (i.e., not whitespace, control characters, etc.), if not, then returnFalse
.message = "hello, world!" print(message.isprintable()) #Output: True
-
isspace()
: Theisspace()
method returnsTrue
if the string consists white spaces, else returnsFalse
.message = " " print(message.isspace()) #Output: True
-
istitle()
: Theistitle()
method returnsTrue
if the first letter of each word of the string is capitalized, else it returnsFalse
.message = "World Health Organization" print(message.istitle()) #Output: True
-
swapcase()
: Theswapcase()
method changes the character casing of the string. Upper case are converted to lower case and lower case to upper case.message = "Hello, World!" print(message.swapcase()) #Output: hELLO, wORLD!