Python Strings

String Data Type

The most commonly used object in any project and in any programming language is String only.
Hence we should aware complete information about String data type.

What is String?

Any sequence of characters within either single quotes or double quotes is considered as a String.

Syntax:
s='seedgroup'
s="seedgroup"

Note: In most of other languages like C, C++,Java, a single character with in single quotes is treated as char data type value. But in Python we are not having char data type. Hence it is treated as String only.

Ex:
ch=’a’
type(ch)

How to define multi-line String literals:

We can define multi-line String literals by using triple single or double quotes.

Ex:
s=”’seedgroup
Software
Solutions”’

We can also use triple quotes to use single quotes or double quotes as symbol inside String literal.

How to access characters of a String:
We can access characters of a string by using the following ways.

  • By using index
  • By using slice operator

By using index:
Python supports both +ve and -ve index.

+ve index means left to right(Forward direction)
-ve index means right to left(Backward direction)

Ex:
s=’seedgroup’

Ex:
s=’seedgroup’
s[0]’s’
s[4]’g’
s[-1]’p’
s[10]IndexError: string index out of range

Note: If we are trying to access characters of a string with out of range index then we will geterror saying : IndexError

 Accessing characters by using slice operator:

Syntax:
 s[beginindex:endindex:step]

beginindex: From where we have to consider slice (substring)
endindex: We have to terminate the slice (substring) at endindex-1
step: incremented value

  • Note:
  • If we are not specifying begin index then it will consider from beginning of the string.
  • If we are not specifying end index then it will consider up to end of the string
  • The default value for step is 1

Ex:
>>> s=”Learning Python is very very easy!!!”
>>> s[1:7:1]
‘earnin’
>>> s[1:7]
‘earnin’
>>> s[1:7:2]
‘eri’
>>> s[:7]
‘Learnin’
>>> s[7:]
‘g Python is very very easy!!!’
>>> s[::]
‘Learning Python is very very easy!!!’
>>> s[:]
‘Learning Python is very very easy!!!’
>>> s[::-1]
‘!!!ysae yrev yrev si nohtyP gninraeL’

Behaviour of slice operator:

s[begin:end:step]

  • step value can be either +ve or –ve
  • if +ve then it should be forward direction(left to right) and we have to consider begin to end-1
  • if -ve then it should be backward direction(right to left) and we have to consider begin to end+1

***Note:

  • In the backward direction if end value is -1 then result is always empty.
  • In the forward direction if end value is 0 then result is always empty.

In forward direction:

default value for begin: 0
default value for end: length of string
default value for step: +1

In backward direction:

default value for begin: -1
default value for end: -(length of string+1)

Note: Either forward or backward direction, we can take both +ve and -ve values for bEgin and end index.

Mathematical Operators for String:

We can apply the following mathematical operators for Strings.

 + operator for concatenation
 * operator for repetition

print(“seed”+”group”) #seedgroup
print(“seed”*2) #seedseed

Note:

  • To use + operator for Strings, compulsory both arguments should be str type
  • To use * operator for Strings, compulsory one argument should be str and other argument should be int

len() in-built function:

We can use len() function to find the number of characters present in the string.

Ex:
s=’seedgroup’
print(len(s)) #9

Checking Membership:

We can check whether the character or string is the member of another string or not by using in and not in operators

s='seedgroup'
print('g' in s) #True
print('z' in s) #False
Program:

s=input("Enter main string:")
subs=input("Enter sub string:")
if subs in s:
    print(subs,"is found in main string")
else:
   print(subs,"is not found in main string")

Output:
D:\python_classes>py test.py
Enter main string: seedgroup
Enter sub string: seed
seed is found in main string

D:\python_classes>py test.py
Enter main string: seedgroup
Enter sub string:python
python is not found in main string

Comparison of Strings:

We can use comparison operators (<,<=,>,>=) and equality operators(==,!=) for strings.

Comparison will be performed based on alphabetical order.

Ex:

s1=input(“Enter first string:”)
s2=input(“Enter Second string:”)
if s1==s2:
print(“Both strings are equal”)
elif s1<s2:
print(“First String is less than Second String”)
else:
print(“First String is greater than Second String”)

Output:
D:\python_classes>py test.py
Enter first string: seed
Enter Second string: seed
Both strings are equal

D:\python_classes>py test.py
Enter first string: seed
Enter Second string: dharshi
First String is less than Second String

D:\python_classes>py test.py
Enter first string: seedgroup
Enter Second string: dharshi
First String is greater than Second String

Removing spaces from the string:

We can use the following 3 methods

rstrip()===>To remove spaces at right hand side
lstrip()===>To remove spaces at left hand side
strip() ==>To remove spaces both sides

Finding Substrings:

We can use the following 4 methods

For forward direction:
find()
index()

For backward direction:
rfind()
rindex()

find():
s.find(substring)

Returns index of first occurrence of the given substring. If it is not available then we will get -1

Ex:
s=”Learning Python is very easy”
print(s.find(“Python”)) #9
print(s.find(“Java”)) # -1
print(s.find(“r”))#3
print(s.rfind(“r”))#21

Note: By default find() method can search total string. We can also specify the boundaries to search.

s.find(substring,begin,end)

It will always search from begin index to end-1 index

Ex:
s=”seedgrouptechnology”
print(s.find(‘g’)) #4
print(s.find(‘e’,7,15)) #10
print(s.find(‘z’,7,15)) #-1

index() method:

index() method is exactly same as find() method except that if the specified substring is not available then we will get ValueError.

Ex:
s=input(“Enter main string:”)
subs=input(“Enter sub string:”)
try:
n=s.index(subs)
except ValueError:
print(“substring not found”)
else:
print(“substring found”)

Output:
D:\python_classes>py test.py
Enter main string:learning python is very easy
Enter sub string:python
substring found

D:\python_classes>py test.py
Enter main string:learning python is very easy
Enter sub string:java
substring not found

Counting substring in the given String:

We can find the number of occurrences of substring present in the given string by using count() method.

s.count(substring) ==> It will search through out the string
s.count(substring, begin, end) ===> It will search from begin index to end-1 index

Ex:
s=”abcabcabcabcadda”
print(s.count(‘a’))
print(s.count(‘ab’))
print(s.count(‘a’,3,7))

Output:
6
4
2

Replacing a string with another string:

s.replace(oldstring,newstring)
Inside s, every occurrence of oldstring will be replaced with newstring.

Ex1:
s=”Learning Python is very difficult”
s1=s.replace(“difficult”,”easy”)
print(s1)

Output:
Learning Python is very easy

Splitting of Strings:

We can split the given string according to specified separators by using split() method.

l = s.split(seperator)

The default seperator is space. The return type of split() method is List

Ex1:
s=”seed group technology”
l=s.split()
for x in l:
print(x)

Output:
seed
group
technology

Joining of Strings:

We can join a group of strings (list or tuple) wrt the given separators.

s = seperator.join(group of strings)

Ex:
t=(‘sunny’,’bunny’,’chinny’)
s=’-‘.join(t)
print(s)

Output: sunny-bunny-chinny

Changing case of a String:

We can change case of a string by using the following 4 methods.

upper()===>To convert all characters to upper case
lower() ===>To convert all characters to lower case
swapcase()===>converts all lower case characters to upper case and all upper case characters to lower case
title() ===>To convert all character to title case. i.e first character in every word should be upper case and all remaining characters should be in lower case.
capitalize() ==>Only first character will be converted to upper case and all remaining characters can be converted to lower case

Ex:
s=’learning Python is very Easy’
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())

Output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy

Checking starting and ending part of the string:

Python contains the following methods for this purpose
s.startswith(substring)
s.endswith(substring)

Ex:
s=’learning Python is very easy’
print(s.startswith(‘learning’))
print(s.endswith(‘learning’))
print(s.endswith(‘easy’))

Output:
True
False
True

To check type of characters present in a string:

Python contains the following methods for this purpose.

isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0 to9 )

isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z)

isdigit(): Returns True if all characters are digits only( 0 to 9)

islower(): Returns True if all characters are lower case alphabet symbols

isupper(): Returns True if all characters are upper case aplhabet symbols

istitle(): Returns True if string is in title case

isspace(): Returns True if string contains only spaces

Demo Program:
s=input(“Enter any character:”)
if s.isalnum():
print(“Alpha Numeric Character”)
if s.isalpha():
print(“Alphabet character”)
if s.islower():
print(“Lower case alphabet character”)
else:
print(“Upper case alphabet character”)
else:
print(“it is a digit”)
elif s.isspace():
print(“It is space character”)
else:
print(“Non Space Special Character”)

D:\python_classes>py test.py
Enter any character:7
Alpha Numeric Character
it is a digit
D:\python_classes>py test.py
Enter any character:a
Alpha Numeric Character
Alphabet character
Lower case alphabet character
D:\python_classes>py test.py
Enter any character:$
Non Space Special Character
D:\python_classes>py test.py
Enter any character:A
Alpha Numeric Character
Alphabet character
Upper case alphabet character

Formatting the Strings:

  • We can format the strings with variable values by using replacement operator {} and format() method.
  • The main objective of format() method to format string into meaningful output form.

Case- 1: Basic Formatting for default, positional and keyword arguments.

name=’seed’
salary=10000
age=48
print(“{} ‘s salary is {} and his age is {}”.format(name,salary,age))
print(“{0} ‘s salary is {1} and his age is {2}”.format(name,salary,age))
print(“{x} ‘s salary is {y} and his age is {z}”.format(z=age,y=salary,x=name))

Output:
seed ‘s salary is 10000 and his age is 48
seed ‘s salary is 10000 and his age is 48
seed ‘s salary is 10000 and his age is 48

Case-2: Formatting Numbers

d--->Decimal IntEger
f----->Fixed point number(float).The default precision is 6
b-->Binary format
o--->Octal Format
x-->Hexa Decimal Format(Lower case)
X-->Hexa Decimal Format(Upper case)

Ex:
print(“The intEger number is: {}”.format(123))
print(“The intEger number is: {:d}”.format(123))
print(“The intEger number is: {:5d}”.format(123))
print(“The intEger number is: {:05d}”.format(123))

Output:
The intEger number is: 123
The intEger number is: 123
The intEger number is: 123
The intEger number is: 00123

Case-3: Number formatting for signed numbers

While displaying positive numbers,if we want to include + then we have to write

{:+d} and {:+f}

Using plus for -ve numbers there is no use and for -ve numbers – sign will come automatically.

print(“int value with sign:{:+d}”.format(123))
print(“int value with sign:{:+d}”.format(-123))
print(“float value with sign:{:+f}”.format(123.456))
print(“float value with sign:{:+f}”.format(-123.456))

Output:
int value with sign:+123
int value with sign:-123
float value with sign:+123.456000
float value with sign:-123.456000

Case-4: Number formatting with alignment

<,>, ^ and = are used for alignment
<==> Left Alignment to the remaining space
^===> Center alignment to the remaining space
===> Right alignment to the remaining space
===> Forces the signed(+) (-) to the left most position

Note: Default Alignment for numbers is Right Alignment.

Ex:
print(“{:5d}”.format(12))
print(“{:<5d}”.format(12)) print(“{:<05d}”.format(12)) print(“{:>5d}”.format(12))
print(“{:>05d}”.format(12))
print(“{:^5d}”.format(12))
print(“{:=5d}”.format(-12))
print(“{:^10.3f}”.format(12.23456))
print(“{:=8.3f}”.format(-12.23456))

Output:
12
12
12000
12
00012
12
-12
12.23512.235

Case-5: String formatting with format()

Similar to numbers, we can format String values also with format() method.

s.format(string)

Ex:
print(“{:5d}”.format(12))
print(“{:5}”.format(“rat”))
print(“{:>5}”.format(“rat”))
print(“{:<5}”.format(“rat”))
print(“{:^5}”.format(“rat”))
print(“{:*^5}”.format(“rat”)) #Instead of * we can use any character(like +,$,a etc)

Output:
12
rat
rat
rat
rat
rat

Note: For numbers default alignment is right where as for strings default alignment is left

Follow Us On