A string is a sequence of characters enclosed within quotes. Strings are one of the most commonly used data types in Python and are versatile for various operations such as manipulation, formatting, and searching. Let’s understand some functions of strings.
To create strings we can either enclose the words in single or double quotes. for example: ‘Hello World’
“Hello World”
Both are correct
print(‘Hello World’)
print(“Hello World”)
Hello World
Hello World
See there is no diffrence between the two sentences the result is same
You can concatenate (join) two or more strings using the + operator.
W1 = “Good”
W2 = “Byeee”
W3 = W1+W2
print(W3)
GoodByeee
You can repeat a string multiple times using the * operator.
name = “Dyuti! ” * 3
print(name)
Dyuti! Dyuti! Dyuti!
You can extract a portion of a string using slicing
text = “Hello, Kitty!”
slice = text[7:12] # 7 is starting index and 12 is ending index, 7th value is␣
↪not included
print(slice)
Kitty
You can access individual characters in a string using indexing
text = “Hello, Kitty!”
first_char = text[0]
print(first_char)
H
NOTE : Indexing starts at 0
we can find the length of a string using the len() function.
text = “Hello, Kitty!”
length = len(text)
print(length)
13
Convert a string to lowercase or uppercase
text = “Hello, Kitty!”
print(text.lower())
print(text.upper())
hello, kitty!
HELLO, KITTY!
Remove whitespace from the beginning and end of a string.
text = ” Hello, Kitty!
” print(text.strip())
Hello, Kitty!
Replace occurrences of a substring with another substring. Part of a string is known as substring
text = “Hello, Kitty!”
result = text.replace(‘Hello’,’Byee’)
print(result)
Byee, Kitty!
Split a string into a list of substrings based on a delimiter
text = “apple,banana,cherry”
fruits = text.split(“,”)
print(fruits)
[‘apple’, ‘banana’, ‘cherry’]
Join a list of strings into a single string with a specified separator
fruits = [‘apple’, ‘banana’, ‘cherry’]
text = “, “.join(fruits)
print(text)
apple, banana, cherry
Use f-strings for more readable and concise string formatting.
This is a newly added function in the latest module of Python.(Python 3.6+).
name = “Bhuvan Bam”
age = 30
message = f”Name: {name}, Age: {age}“
print(message)
Name: Bhuvan Bam, Age: 30
text = “Hello, Kitty!”
result = text.replace(‘Hello’,’Byee’)
print(text)
print(result)
Hello, Kitty!
Byee, Kitty!
See the original string which is “text” even after modifying when we print “text” again, we get the same answer. This makes it clear that Python does not modify the existing string but it rather makes a new string. Hence, Strings are immutable i.e. cannot be changed
