0% found this document useful (0 votes)
4 views

String

The document provides a comprehensive overview of strings in Python, detailing their characteristics, such as immutability and indexing. It explains string operations, including concatenation, replication, membership, and comparison, along with various built-in string methods for manipulation. Additionally, it covers string slicing, traversing, and common functions like capitalize, title, and split.

Uploaded by

addie20101979
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

String

The document provides a comprehensive overview of strings in Python, detailing their characteristics, such as immutability and indexing. It explains string operations, including concatenation, replication, membership, and comparison, along with various built-in string methods for manipulation. Additionally, it covers string slicing, traversing, and common functions like capitalize, title, and split.

Uploaded by

addie20101979
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

STRINGS in PYTHON

Strings
A string datatype hold string data-any number of valid characters into a set
quotation marks. Each character in a string is a Unicode character. A string can
hold any type of known characters ie letters, numbers and special characters.
Python strings are character enclosed in quotation of any type-single quotation
mark, double quotation mark and triple quotation mark. Empty or null string is
a string that has 0 characters. Examples of valid string:-“abcd”, “1234”,
‘$%^&’.
Python strings are immutable. Strings are sequence of characters where each
character has a unique position called index. Index of a string begin from 0 to
length-1 in forward direction and -1, -2, -3….. –length in backward direction.
Strings
A Python string is a sequence of characters and each characters and each character
can be individually accessed using its index. Strings in Python are stored as individual
characters in contiguous location, with 2 way index for each location.
Let us consider the string say str1=“DPS Bopal”
It will be stored as

Forward Indexing 0 1 2 3 4 5 6 7 8
D P S B o p a l
Backward Indexing -9 -8 -7 -6 -5 -4 -3 -2 -1
Length of the string variable can be determined using len(<string>) function.
str1[1]=‘P’ str1[4]=‘B’ str1[7]=‘a’
str1[-4]=‘o’ str1[-9]=‘D’ str1[-2]=‘a’
The index is also called subscript and index is enclosed square brackets.
Strings
In a string, there is no index equal to the length of the string.
For example:
str1=“DPS Bopal”
print(str1[9]) # will show error.

Strings are immutable. It is not possible to change or add or delete individual


letters in a string.
str1[3]=“-” #Not possible to replace a character
The above statements will show error.
String Operators-+,* ,in & not in:
+ operator performs concatenation
Example:
str1=“DPS”
str2=“Bopal”
str3=str1+“ ”str2 #str3 will be DPS Bopal
print(2+3) # will print 5
print(“2”+“3” # will print 23
print(“2”+3) #Invalid because datatype is not same.
String Operators
* operator performs replication:
If 2 operand are numbers, it perform multiplication. But if you multiply one
string with an integer result in replication.
Example:
str1=“DPS”
print(2 * 3) # will print 6
print(“2” * 3) # will print 222
print(str1 * “3”) # will print DPSDPSDPS
print(“2” * str1) # is Invalid because both operands are string
String Operators
membership operators in and not in:
in # returns True if character/substring exists in the given string.
not in # returns False if character/substring not exists in the given string
Example:
str1=“DPS”
print(“D” in str1) # True
print(“d” in str1) # False
print(“D” not in str1) # False
print(“J” not in str1) # True
print(“PS” in str1) #True
String Operators
comparison operators:
in # returns True if character/substring exists in the given string.
not in # returns False if character/substring not exists in the given string
Example:
str1=“DPS”
Str2=“dps”
print(“a” ==‘a’) # True
print(str1== str2) # False
print(str1!=“DPS”) # False
print(str2!=“DPS”) # True
String Operators
comparison operators:
Internally Python compares using Unicode values called ordinal values. For
most common characters, the ASCII values and Unicode values are the same.
‘a’ < ‘A’ #will give False Characters Ordinal Value

‘ABC’ > ‘AB’ #will give True ‘0’ to ‘9’ 48 to 57


‘A’ to ‘Z’ 65 to 90
‘abcd’ > ‘abcD’ #will give True
‘a’ to ‘z’ 97 to 122
Note:
ord() function takes single character and returns corresponding ordinal
Unicode value. Example: print(ord(‘A’)) will print 65.
chr() function takes the ordinal value in integer form and return the character
corresponding to that ordinal value. Example print(chr(65)) will print ‘A’.
String Slices
In Python the term string slice refers to a part of the string, where strings are
sliced using a range indices. For a string say str1, if we give str1[i:j:k] where i is
initial index, j is last index and k is the skip value. Python will return a slice
from i to j-1 with skip value k.
0 1 2 3 4 5 6 7 8
String Slices D P S B o p a l
Examples:
-9 -8 -7 -6 -5 -4 -3 -2 -1
Consider the following string s1=“DPS Bopal”
print(s1[7]) # will give ‘a’
print( s1[-2]) # will give ‘a’
print( s1[1:5]) # will give ‘PS B’
print( s1[-7:-4]) # will give ‘S B’
print( s1[:6]) # will give ‘DPS Bo’
print( s1[4:]) # will give ‘Bopal’
print( s1[2:-2]) # will give ‘S Bop’
print( s1[1:8:2]) # will give ‘P oa’
0 1 2 3 4 5 6 7 8
String Slices D P S B o p a l
Examples:
-9 -8 -7 -6 -5 -4 -3 -2 -1
Consider the following string s1=“DPS Bopal”
print( s1[::2]) # will give ‘DSBpl’
print( s1[-9:-4:2]) # will give ‘DSB’
print(s1[-1:-4:-1]) # will give ‘lap’
print( s1[::-1]) # will give ‘lapoB SPD’
print( s1[-10]) # will give error: invalid index out of bound
print( s1[9]) # will give error : invalid index out of bound
print( s1[8:15]) # will give ‘l’
print( s1[9:15]) # will give empty string
Note: Index out of bounds causes error with string but slicing string outside the
bounds does not cause error.
Traversing a String
Traversing refers to iterating through the elements of a string, one character at
a time by accessing through the unique index of each character. Traverse
through a string can be done using a loop. For Example
s1=“INDIA”
#will print all characters in a line separated by ‘-’
for i in s1:
print(i,end=“-”)
#will print all characters one below other
for i in s1:
print(i)
#will print all characters in a line separated by ‘-’
for i in range(len(s1)):
print(s1[i],end=“-”)
WAP to display the string in reverse order:
s1=input(“Enter a string”)
#using +ve index
for i in range(len(s1)-1,-1,-1)):
print(s1[i],end=“-”)
#using –ve 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
Python offers many built in functions and methods for string manipulation.
Consider the string s1=“DPS Bopal”
capitalize() Converts the first character to upper case.
print(s1.capitalize()) #will print Dps bopal
title() Converts the first character of each word to upper
case.
print(s1.title()) #will print Dps Bopal
upper() Converts a string into upper case
print(s1.upper()) #will print DPS BOPAL
lower() Converts a string into lower case
print(s1.lower()) #will print dps bopal
String Functions and Methods
isalpha() Returns True if all characters in the string are in the alphabet.
print(s1.isalpha()) #will print False
isalnum() Returns True if all characters in the string are alphanumeric
print(s1.isalnum()) #will print True
isdigit() Returns True if all characters in the string are digits
print(s1.isdigit()) #will print False
islower() Returns True if all characters in the string are lower case
print(s1.islower()) #will print False
isupper() Returns True if all characters in the string are upper case
print(s1.isupper()) #will print False
String Functions and Methods
isspace() Returns True if all characters in the string are
whitespaces
print(s1.isspace()) #will print False
isnumeric() Returns True if all characters in the string are
numeric
print(s1.isnumeric()) #will print False
istitle() Returns True if the string follows the rules of a title
print(s1.istitle()) #will print False
startswith() Returns true if the string starts with the specified
value
print(s1.startswith(‘D’) #will print True
endswith() Returns true if the string ends with the specified value
print(s1.endswith(‘L’) #will print False
String Functions and Methods
index() Searches the string for a specified value and returns the
position of where it was found. If not found, it returns
error.
print(s1.index(“S P”,1,8)) #will print 2
find() Searches the string for a specified value and returns the
position of where it was found. If not found, it returns -1.
print(s1.find(‘S’)) #will print 2
count() Returns the number of times a specified value occurs in a
string
print(s1.count(‘a’)) #will print 1
swapcase() Swaps cases, lower case becomes upper case and viceversa
print(s1.swapcase()) #will print dps bOPAL
replace() Returns a string where a specified value is replaced with a
specified value
print(s1.replace(‘ ’,-)) #will print DPS-Bopal
String Functions and Methods
split() Splits the string at the specified separator, and
returns a list
print(s1.split(‘ ‘)) #will print [‘DPS’, ‘Bopal’]
list1=[‘DPS’, ‘Bopal’]
join() Converts the elements of an iterable into a string
print(“#”.join(list1) #will print DPS#Bopal
s2=“ DPS Bopal ”
lstrip() Returns a left trim version of the string
print(s1.lstrip()) #will print ‘DPS Bopal ’
rstrip() Returns a right trim version of the string
print(s1.rstrip()) #will print ‘ DPS Bopal’
strip() Returns a trimmed version of the string
print(s1.strip()) #will print ‘DPS Bopal’

You might also like