Created by Turbolearn AI
Strings in Python
Here's a look at the fascinating world of strings in Python, represented by a visually striking graphic design featuring wavy
blue lines on a gradient background. The image adds an aesthetic touch and complements the concept of fluidity and
dynamic movement associated with strings.
Definition of a String
A string datatype holds string data, which can be any number of valid characters enclosed in quotation marks.
Each character in a string is a Unicode character. Strings can hold letters, numbers, and special characters.
Python strings are enclosed in quotations (single, double, or triple). An empty or null string contains zero characters.
Examples of valid strings: "abcd", "1234", '%$^&'
Immutability
Python strings are immutable, meaning they cannot be changed once created.
String Indexing
Strings are sequences of characters, each with a unique position called an index.
Indexing starts from 0 to length-1 in the forward direction.
Indexing starts from -1 to -length in the backward direction.
Consider the string str1 = "DPS Bopal":
0 1 2 3 4 5 6 7 8
String D P S B o p a l
Forward Indexing 0 1 2 3 4 5 6 7 8
Backward Indexing -9 -8 -7 -6 -5 -4 -3 -2 -1
str1[1] = 'P'
str1[4] = 'B'
str1[7] = 'a'
str1[-4] = 'o'
str1[-9] = 'D'
str1[-2] = 'a'
The length of a string can be determined using the len(<string>) function. Attempting to access an index equal to the
length of the string will result in an error.
String Operators
Page 1
Created by Turbolearn AI
Operator Description Example
str1 = "DPS", str2 = "Bopal", str3 = str1 + " " + str2
+ Concatenation
(str3 is "DPS Bopal")
* Replication str1 = "DPS", print(str1 * 3) (prints "DPSDPSDPS")
Returns True if a character/substring exists in the
in
string
Returns True if a character/substring does not exist
not in
in the string
print(2 + 3) # Output: 5
print("2" + "3") # Output: 23
# print("2" + 3) # This will cause an error because of different data types
Comparison Operators
Python compares strings using Unicode values (ordinal values). ASCII values are the same as Unicode values for most
common characters.
Examples:
'a' < 'A' # Returns False
'ABC' > 'AB' # Returns True
'abcd' > 'abcD' # Returns True
Characters Ordinal Value
'0' to '9' 48 to 57
'A' to 'Z' 65 to 90
'a' to 'z' 97 to 122
ord() function: Returns the Unicode value of a character (print(ord('A')) will print 65).
chr() function: Returns the character represented by a Unicode value (print(chr(65)) will print 'A').
String Slices
A string slice refers to a part of the string, sliced using a range of indices. For a string str1, str1[i:j:k] returns a slice from
index i to j-1 with a skip value of k.
Consider the string s1 = "DPS Bopal"
0 1 2 3 4 5 6 7 8
String D P S B o p a l
Forward Indexing 0 1 2 3 4 5 6 7 8
Backward Indexing -9 -8 -7 -6 -5 -4 -3 -2 -1
Examples:
Page 2
Created by Turbolearn AI
print(s1[7]) # Output: a
print(s1[-2]) # Output: a
print(s1[1:5]) # Output: PS B
print(s1[-7:-4]) # Output: S B
print(s1[:6]) # Output: DPS Bo
print(s1[4:]) # Output: Bopal
print(s1[2:-2]) # Output: S Bop
print(s1[1:8:2]) # Output: P oa
print(s1[::2]) # Output: DSBpl
print(s1[-9:-4:2]) # Output: DSB
print(s1[-1:-4:-1]) # Output: lap
print(s1[::-1]) # Output: lapoB SPD
print(s1[8:15]) # Output: l
print(s1[9:15]) # Output: Empty string
Note: Index out of bounds causes an error with indexing, but slicing outside the bounds does not cause an error.
Traversing a String
Traversing a string means iterating through its elements (characters) one at a time using the index of each character.
s1 = "INDIA"
# Will print all characters in a line separated by '-'
for i in s1:
print(i, end="-")
# Will print all characters one below the other
for i in s1:
print(s1[i], end="-") #this line will cause an error since i will hold the character rather than the index
# Program to display the string in reverse order:
s1 = input("Enter a string")
# Using positive index
for i in range(len(s1)-1, -1, -1):
print(s1[i], end="-")
# Using negative index
x = -(len(s1)-1)
for i in range(-1, x, -1):
print(s1[i], end="-")
# Alternate method
str = ""
for i in s1:
str = i + str
print(str)
String Functions and Methods
Consider the string s1 = "DPS Bopal " for the following examples.
Page 3
Created by Turbolearn AI
Method Description Example
capitalize() Converts the first character to upper case print(s1.capitalize()) # Output: Dps bopal
Converts the first character of each word to upper
title() print(s1.title()) # Output: Dps Bopal
case
upper() Converts a string into upper case print(s1.upper()) # Output: DPS BOPAL
lower() Converts a string into lower case print(s1.lower()) # Output: dps bopal
Returns True if all characters in the string are in the
isalpha() print(s1.isalpha()) # Output: False
alphabet
Returns True if all characters in the string are
isalnum() print(s1.isalnum()) # Output: False
alphanumeric
isdigit() Returns True if all characters in the string are digits print(s1.isdigit()) # Output: False
Returns True if all characters in the string are lower
islower() print(s1.islower()) # Output: False
case
Returns True if all characters in the string are upper
isupper() print(s1.isupper()) # Output: False
case
Returns True if all characters in the string are
isspace() print(s1.isspace()) # Output: False
whitespaces
Returns True if all characters in the string are
isnumeric() print(s1.isnumeric()) # Output: False
numeric
istitle() Returns True if the string follows the rules of a title print(s1.istitle()) # Output: False
Returns True if the string starts with the specified
startswith() print(s1.startswith('D')) # Output: True
value
Returns True if the string ends with the specified
endswith() print(s1.endswith('l')) # Output: False
value
Returns the index of specified value, shows error if
index() print(s1.index("S B", 1, 8)) # Output: 2
value not found
Returns the index of specified value, returns -1 if
find() print(s1.find('S')) # Output: 2
value not found
Returns the number of times a specified value
count() print(s1.count('a')) # Output: 1
occurs in a string
Swaps cases, lower case becomes upper case and
swapcase() print(s1.swapcase()) # Output: dps bOPAL
vice versa
Replaces a specified value with another specified
replace() print(s1.replace(' ' , '-')) # Output: DPS-Bopal-
value
Splits the string at the specified separator, and
split() print(s1.split(' ')) # Output: ['DPS', 'Bopal', '']
returns a list
list1 = ['DPS', 'Bopal'], print("#".join(list1)) #
join() Converts the elements of an iterable into a string
Output: DPS#Bopal
s2 = " DPS Bopal ", print(s2.lstrip()) # Output: 'DPS
lstrip() Returns a left trim version of the string
Bopal '
rstrip() Returns a right trim version of the string print(s2.rstrip()) # Output: ' DPS Bopal'
strip() Returns a trimmed version of the string print(s2.strip()) # Output: 'DPS Bopal'
Page 4