Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views42 pages

01-String Syllabus Complete

The document provides a comprehensive overview of strings in Python, including their definition, properties, and methods for creating and manipulating them. It covers topics such as string mutability, escape sequences, string operations like concatenation and repetition, and formatting techniques. Additionally, it explains how to handle special characters and multi-line strings using various quoting methods.

Uploaded by

compnetworxxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views42 pages

01-String Syllabus Complete

The document provides a comprehensive overview of strings in Python, including their definition, properties, and methods for creating and manipulating them. It covers topics such as string mutability, escape sequences, string operations like concatenation and repetition, and formatting techniques. Additionally, it explains how to handle special characters and multi-line strings using various quoting methods.

Uploaded by

compnetworxxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Intro

Defining a String
Creating a String -
Single quotes and Double quotes Triple Quotes Empty String
String Properties
Mutability and Immutability: Are strings mutable?
Escape Sequence:
Escape sequence for Broken String \ backslash
Writing a Multi Text in single Line \
Writing a Multiple Line in new Separate Line
\n Backslash n is a new line
\t add a tab to the text
Escape Sequence for File-path \
Double slash\\
String Operations in Python
Variable String Concatenation
String Repetition
Convert Other Data type in String
String Formatting Using
% string formatting specifier
.format()
f-strings
String Method
capitalize , lower, upper, title, count ,strip, split, join, find, replace, center,
inex
String Indexing
String Variable
Intro: To work with Text in Python u need a String
Strings are the most popular Data Type in python
Strings are used in Python to Record Text Information it allowing
us to work with Textual Data in Python which it is used as how we
want to display.
Defining a String
A String is a sequence of characters or an Order
Collection arrays of bytes representing Unicode
character since python doesn’t have any character data
type a single character in python is simply a string
whose length is one
- numbers letters and symbol are called characters
so string can be letters or numbers e.g.: Letters including 0
any Numbers or Digit
A string can also be special characters or symbols
eg : special characters like dollar sign
A string can be spaces, punctuation everything that
include by quotes Its represented in python with strings data type
even though integer number enclosed in string quotes it will be
classified as a string
str1 = "10"
print(type(str1))
Imp! Strings can have any numbers of characters in it
Are strings mutable? No strings are not mutable!

Strings are immutable String Properties


String has immutable properties meaning(it cannot be changed
once we declared it in a program )
String is immutable object every time we define a string its object is
created and we try to manipulate the same string a new objects get
created
Its important to know that Strings have a an important properties known as
immutability
A Python String is Immutable u cannot change the value of it in other words you
cannot change the character of a string once you made string, you cannot change the
element within them so lets try to the change first letter to S in our hello world
str[0]=’x’#get an error
however
A string variable might allow its elements to be mutated and it's length changed, or it
may be fixed (after creation).
string = "string"
new_string = string.replace('t', 'T')
print(new_string)
Now some people think how we change name variable if strings are immutable?
remember one thing in Python we can change the value of variable anytime but other
methods cannot change our strings or we cannot change particular character from
string(Immutability)

Strings in python unlike other languages are immutable


data type you can't change string in place but can copy
parts of strings to another string to change it
How do we create a string in python?
Creating a String
whenever we work with string or text
surround your text with quotes meaning
Strings goes inside quotes u can define a String with either Single
or Double Quotes so whenever we create string in Python u need to
use Quotes either single or Double that's personal preference
According to PEP 8 style Guide for Python Code Single quoted
strings and double-quoted strings are the same
so either Single or Double Quotes are fine basically choose one and
stick to it
" Python treat single Quotes the same as double quotes
Basic Example
*Let us print Hello world using Python Built in Print function
and then in parenthesis pass the text value surrounded with
single or double quotation
print('hello world')# Python print instruction hello world enclosed in
Single Quotes
print("hello world")# Python print instruction hello world enclosed in
Double Quotes
that will also work
Lets save this and run this file to see our output
python3 using auto tab out name of a file
now you can see that how we give a print instruction
to wrote out Hello world and also comes to know that both the
quotes act similarly You (and the interpreter) can identify strings
because they are enclosed in quotation marks either Single or
Double quotes
--------------------------------
Triple Quotes: Multi Line Comment:
Use of Triple Quotes on multiple line for comment purpose
If we need to create Multi Line String or To format a long String
we use Triple Quotes at the beginning and the end of our string
suppose we have variable name message which we want to include
in the body of an email we can use triple quotes to format like this
message = """ This strings run Multi Line Hey Mr X This is
Mr Y from python World
Blah Blah Blah"""
print (message)
(""" This strings run Multi Line .....""")# Triple Quotes for Multi
Line
Doc String: Python Doc Strings are strings used right after the
definition of a Function Method Class or Module
They used to document our Code

Note! I also use three single quotes


More in depth in Multi Line later in this Video
Empty String:
The empty string ''(two quotes with nothing between them)

Make strings in three different ways


so if u are wondering if there is a difference between the single and
double quotes and its really depend on what text you have in your
string
For Example so what we you do if you have single quotes and a
Punctuation mark in your string
Let's say we create a string with a single quote
'I'm Python Programmer' # since we define a single string with three
single quotes this will create a broken string
you cannot use single quotes inside single quotes
#print('I'm Python Programmer')#u get an error
The problem here is Python see this single quotes with our text as
being the end of the string and it's not going to know what to do
with what comes after single quotes because it think that where the
string is closing so if u run u will get an error there a couple of
different way to handle
Escape sequence for Broken String \ or Escape Characters:
'I\'m'
escaped '
Understanding Escape Character in Strings
we could escape characters this single quotes with a backward
slash right above or besides the enter key on some keyboard
'I\'m Python Programmer' python interpreted as part of the
string rather than the quotes that’s end the String
so here using backward slash
we fix broken strings using the Escape Sequence
Back slash Characters has Special Meaning in the Strings u escape
the character that follows it to give that character special meaning
Characteristics of beginning and ending of string
so there a lots of control character in python
now if i run this python know this single quotes doesn't close out
the string another way to handle that is to u can use the combination
of double and single quotes
use double quotes outside of the string which contained single quotes
code:
print("I\'m a Python Programmer")
"I'm Python Programmer" so if we know that our string contains
single quotes than we use the double quotes outside that string than
Python knows that single quotes isn't the end of the string but it
doesn't necessarily mean that double quotes are better because it
goes both ways if your string contains double quotes in the message
then u use single quotes outside
so if you start with a one type than you end with that type
you can use' single quotes' inside "Double quotes"
print("hello 'world' world")
Or :Double Quotes" inside' Single Quotes'
print('hello "world" world')
another way using multi line quotes
now if we create a multi line string and one way we can do this by
using triple quotes at the beginning and at the end of our string
print(""" I'am a Python Programmer """)
Escape sequence for bypass double quote
Arabic_Greeting_Message="\"Ahlan Wasalan\"\n\"Marhaba\"
\n\"As Saalam o ale kum\" \n"
print(Arabic_Greeting_Message)
Example:
Escape Sequence for writing Multiple line for a Single String line :
Suppose we are writing something with a separated line
so if we check the value of that string a new line character created
when we use enter button in the particular string denoted \
backslash so to get rid of them so
whenever we want a new line to be inserted we use backslash \
or when you want to separate your line
create a variable name my_name and add a string "Shahid"
and if i print that i get the result
so what if a i add multiple lines to the string instead of single
characters or single lines
let me try out to add long string all i have to do is to
add \backslash at the end of each line and enter can able to add
more characters to the long string so lets add some sample text
more line to be add use back slash once i satisfied i don’t want to
add no more lines use quotation to end my string now if i try to
print
Code:
my_string = "long \
sample text \
more sample text"
print(my_string)
print(my_string)# we have multiple line of string but are in one
single string line with same result even we write in three lines
Multiple Line in Separate Line:
so what if need to get three line of string in three different lines
all I have to do is to use backslash\ n it will leave a line while
printing
another_string ="another \n new line \n another line \n"
print(another_string)# three seperated line got printed
Arabic_Greeting_Message="Ahlan Wasalan\nMarhaba \nAs
Saalam o ale kum \n"
print(Arabic_Greeting_Message)
Imp:
so thats means if i need to leave a line i need to backslash n
but i need to write a line in sepaerate but in dont need to print that
i use slash only
Escape Sequence for File-path \
escape character also be used in file path
lets take a real example and do the fun so what if i need to take a
directory address
lets create a new variable and store my directory address
specify a certain path to a file
generally we do display path like this
c:\users\
my_dir ="C:\users\download\nodejs"
if i do that and print this particular directory
print(my_dir)
you will get the path with nodejs in different line what happen
python think that we are using slash n as escape character so they
left a new line and print odejs but we do want so if we want to skip
this all I have to do is use double slash
my_dir ="C:\users\download\\nodejs"
thats means if use double slash it would be printed as slash
print(my_dir)# it wil printed correctly now
double used to avoid the functionaltiy oif escape chareacter amd
telling the pytohn intrpepreter that we are not using slash n
same follows with different functionalities
suppose ineed to use some quoation mark inisde of string let me
take a new string
new_string= " John said \"Hello\" to me"
print(new_string)
here my main string was Jhon said "Hello" to me which i like to
be printed out but what happen i will get error as invalid Sysntax
because you cannot use two quotation mark in a single string so if
in ed to use them all i have to do is use a back slash so al i have to
do is add a backslash before hello opening quotaion mark and
after thats means it would give a refrence to our Python
Intrepreter that dont consider it as Ending quotaion now if i do
that so no error and print
new /-string= " John said \"Hello\"to me"
print(new_string)
so what if iuse singlre string instead of double before and after
our sentence we can do that we will get no wrror
new /-string= 'John said "Hello"to me'
but what happend if i use single quoation mark and some how our
string has single quoation mark inside it also
suppose take an example as
my_pen = 'Shahid's Pen'
error will be genrated so if iwant o that all i ahve to do is
backslash and then i use quoatation mark
my_pen = 'Shahid\'s Pen'
learn the escape character Chart or Escape sequence in Python
\ go to next line or use multi line statement use backward slash
\" Print the next character as a Double Quote ,not a string closer
\' Print the next character as a Single Quote ,not a string closer

******************************
\n Print a new line character
>>> line = "One\nTwo"
>>> print(line)
One
Two
************************
\t Print a new tab character
Multiline String using escaped tab
z ="""X\tY\tZ
1\t2\t3"""
print(z)
result
X Y Z
1 2 3
****************************
\t Print a carriage return (not used very often)
\$ Print the next character as a Dollar, not as a part of a variable
\\ Print the next character as abackslash, not an escape character
Note: A Statement is simply an Instructions that is going to be
Executed by Python Interpreter
Escape sequence as normal text prefixing with black slash or escape
character symbol
course = "Python \" Programming"

String Operations in Python


We will learn all about String Operations in Python
STRING CONCTENATION:
String concatenate take two and more strings and Combining
or Unified those Strings either literal string or string variable
in python with + operators as we do with numbers
Plus Operator used to concatenate (paste or add) the two string
togetherCode:
Concatenating literal string together
print("Hello "+" World")
print ('Hello ! ' + 'World')
print("This String "+" is Awesome!")
print("conctena"+"tion")
print("hello","there")#using comma for space

Concatenating string variable together


first_word ="Hello" # Hello string inside double quotes
second_word='There'
print(first_word +second_word)

first_word='Shahid'
second_word="Nasim"
print(first_word + " " + second_word) # Pyton doesnt any spaces while conctenating
strings so we had to explicitly add two quotation mark to add spaces in between if
you now print(first_word,second_word)# notice that space is automatically added by
print function because first_word and second_word neither have spaces and also add
a new line whihc we dont see here
white space does matter in between the quotation mark
Here Plus Operator used to concatenate (paste) the two string variable together
plus operator also used to add values in Python

Another Explanation
More details can be earn in Operators in Python Lecture Video
Combine String together using + Operator make sure u have a
space left and right side of plus operator to avoid mixing words
What can we do with the String
we can concatenate them this means unified to more strings into a
single string you can do this with the plus operator like you do
when you adding with numbers
x="Cisco"
y=""2691"
x+y

Combination Operation String and a Number


Normally you cannot concatenate string with numbers
>>> print 'red' + 3
Traceback (most recent call last):
File "", line 1, in
TypeError: cannot concatenate 'str' and 'int' objects
>>>
Python doesn't know how to add a word and a number, so it says
"cannot concatenate 'str' and 'int' objects."
A word that you put in quotes is just a string of letters called a "str"
in python.
Numbers that don't have a decimal point are integers and are called
"int" in python.
You can't add a str and an int.
But you can turn a number into a string if you use the str() function.
>>> print 'red' + str(3)
red3
>>>
type ('hello world')# Strings in Python are shown as the variable type str
<class 'str'>
str in built python function can covert integers into string it comes
with many handy features converts its argument to a string meaning
its accepts an object such as a number and returns a string object
>>> str(32)
'32'
>>>type(str)
>>> str(3.14159)
'3.14159'
>>>type(str)
>>>('32')# Quotes turn digit into strings
Another Explanation
as a Example 25 is an Integer but i can use str function to change it
into string using - str function
We can convert the integer to a string, via the str() function
a=15
print(type(a))
print(type(str(a)))
print(type(str(1.0e5)))

x= True
print(type(str(x)))
Boolean Values Changes to string
Combination Operation String and a Number
Ex: – Concatenate string and int
a = "Hello, I am in grade "
b = 12
what would happen if we have a string and an int on both sides of the operand?
print(a + b)
Python is a dynamically typed language, we would not face any error during
compilation, but rather, we get a Runtime Error. (More specifically, a TypeError
exception is raised)
Solution
Using str()
We can convert the integer to a string, via the str() function
b=str(12)
This is the most common way to convert an integer to a string
String Repetition - String Multiplication by using the
Multiplication Operator to duplicate Strings and string values
Repeat Strings as many time u multiplied it
Code:
word ="hello"
print(word*5)
or
word ="hello" *4
print (word)
or in the intrepreter
word
Addition and Multiplication have different application for
string Subtraction and Division do not
Code
x*3
String Formatting |
We will be going over different ways to format strings, and also a
lot of useful string methods.
there are four different ways to perform string formatting:-
Formatting with placeholders.
Formatting with. format() string method.
Formatting with Interpolation string literals, called f-
strings
Formatting with Template string

Formatting with placeholders: old style using percent


the old way to format strings with placeholders in Python is simpler
% string formatting using modulo operator or percentage sign with a character we
have option such as d for decimal s for string i for integer f for float h for
hexadecimal o for octal e for exponential %% for literal percentage
The modulo % is also known as “string-formatting operator”.
% allows us to construct strings, replacing parts of the strings with the data stored in
variables.
Here is an example of % string formatting:
Code:
print('%s %s ' % ('greeting','name'))#old
print('{} {}' .format('greeting','name'))#new

name=”Bob”
errno=50159747054
#print('Hey %s there is a ErrorNo 0x%x' %(name,errno))

#greeting="World"
#print('%s %s ' % ('greeting','name'))#old
#print('Hey %s there is a ErrorNo 0x%x' %(name,errno))
#greeting="World"
#print('%s %s ' % ('greeting','name'))#old

name ='Eric'
age =17
print("Hello, %s. You are %s." % (name, age))
When applied to integers, %n is the modulus operator
camels = 42
'%d' % camels
'42
model='2600XM'
WanSlots=2
ios=12.4
print("Cisco Model: %s, %s Wan Slots, IOS %s" % ("2600XM","2","12.4"))
print("Cisco Model: %s, %s Wan Slots, IOS %s" % ("2600XM","2","12.4"))

Another Example:
name ="GNS3"
language ="Python"
cost = 0
message1 ='Hello %s community, time to start using %s The Cost is %i or
$%7.2f if you prefer .' %(name,language, cost, cost)
print(message1)
#first String Value replace with name variable value
#second string value replaced with language varaible value
#thirdly replaced with integer and float with cost varaible value
#float formatting change with prcision .2f
#have sapces in front of dollar using dollar sighn with number of spaces
specified

Python string Dot format() method


formats the given string into a nicer output in
Python.
this approach can lead to problems when writing longer string
in this tutorial we will explore the new preferred Python string formatting method using
curly brace
.
print('{0} {1}' .format('greeting','name'))#new positional
Note! This operation is not available with old-style formatting.
#print('{} {}' .format('greeting','name'))#new
#print('{0} {1}' .format('greeting','name'))#new positional
first_name='Eric'
last_name="Marshall"
print("My name is {} {}" .format(first_name,last_name))#default argument
print("My nmae is {first_name} {last_name}" .format(first_name ="Eric",last_name=
"Marshal"))#keyword argumknets
print("My nmae is {0} {1}" .format("Eric","Marshal")) postional argument
print("My nmae is {0} {last_name}" .format("Eric",last_name="Marshall"))#mixed
argument

# default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))
# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))

# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346))

# mixed arguments
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))

Useful Links:https://www.programiz.com/python-
programming/methods/string/format
String Formatting Method- The format()
method returns the formatted string.-
The Python string formatting method gives us better control over how we can modify
string objects.
The old way has some limitations to how string objects can be modified.
When formatting a string in Python using the format method we use curly
brackets({}) for placeholders versus the old way where we would use the percentage
or modulo symbol(%). If you need to use curly brackets in your string itself and you
do not want it to be a placeholder then we can utilize two curly brackets to escape the
brackets.
Python String Formatting Method Syntax
'String Object {placeholder}.format(arguments)
'String Object {placeholder}' - This our string object that will be modified by the
format string method.
The {placeholder} is where we are able to insert content into the string object to
create a new string object that contains the new content.
.format(arguments) - The format string method allows us to modify string objects to
create a new string object with some inserted content.
The arguments are the content that is going to replace the placeholders in the
original string object.
Examples of The Python String Formatting Method
Code
Format String Method - Example 1
#Example 1
'This is a {} in Python'.format('string')
'This is a string in Python'
print('My Name is {}'.format('Shahid'))

Example 1 Explained
'This is a {} in Python'.format('string') –
In this example, we set up a string object that contains a placeholder({}).
The placeholder is where we are about place our argument. The format string
method allows us to insert the content(argument) into our string object which will
return us a new string object.
The 'string' is our argument which will replace the curly brackets.
'This is a string in Python' - We are returned a new string object that contains our
argument in the same position that our placeholder was in the previous string object.
Format String Method - Example 2
'This is our {} in {}'.format('string', 'Python')
'This is our string in Python'
print("Muslim Celebrate {} and {} ".format('Eid', 'Bakrid'))
Example 2 Explained
'This is our {} in {}'.format('string', 'Python') - In this example,
we create a new string object that contains two placeholders which will be replaced
by our arguments which are contained in the right side of the format string method.
When adding more than two arguments we must separate them with a comma. In
this case when we run this line of code Python's format string method will take the
first argument and place in the first placeholder position and then the second
argument and place it in the second placeholder position.
'This is our string in Python' - We are returned a new string object with the first and
second place holders replaced by the first and second arguments.
Format String Method - Example 3
'This is our {1} in {0}'.format('Python', 'string')
'This is our string in Python'
Example 3 Explained
'This is our {1} in {0}'.format('Python', 'string') - In this example, we create a new
string object which is similar to example 2 but notice we place a number 1 in the first
place holder and a number 0 in the second placeholder.
We also change the order of the arguments in the format string method. When this
line is ran Python will look at the number contained in the placeholders which is
actually index position of the arguments.
It will then locate the argument via the index position and insert it into the new string
object.
'This is our string in Python' - As you can see the format string method found the
first index position which is our second argument and inserted that in our new string
object. Then the format string method found our next argument at the 0 index
position.
Format String Method - Example 4
person = {'name': 'Eric', 'age': 74}

"Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])


'Hello, Eric. You are 74.'

'We are learning {language} {version}'.format(language='Python', version='3')


'We are learning Python 3'
Example 4 Explained
'We are learning {language} {version}'.format(language='Python', version='3') –
We create a string object that contains our placeholders which are now represented
by curly brackets and names. These names will be used to match the arguments with
your place holders.
'We are learning Python 3' - We are returned a new string object that replaces the
placeholders with the appropriate arguments.
Format String Method - Example 5
language = ('Python', '3')
'We are learning {0[0]} {0[1]}'.format(language)
'We are learning Python 3'
language = ('Python', '3') - We create a tuple that contains two values.

Another Example:
print("New way of using Braces Dot Format Method" )
dns= '8.8.8.8' #google dns server
vrf ="Internet" #vrf for MPLS Deployment
ping = 'ping' + " " + dns + " " + "vrf" + " " + vrf # vaiable string conctenation with spaces
print(ping)

#this approach not easy to manage and complicated when using complex program

ping1=("ping {} vrf {}" .format(dns,vrf))


#format method takes dns and vrf as an argument and they will be inserted into curly
braces
#no need to apply str
print(ping1)
#lot simpler and esy to read
print("-------------------------")
ping2 = 'ping{} vrf {}'
print(ping2)
print("-------------------------")

runcommand = ping .format(dns,vrf)


print(runcommand)

String Function and Method -


String support various methods
Data type we are going to review are going to have certain
methods available to us that gives us access to a lots of useful
functionality now when I say method a lots of people wonder
what’s the difference between method and a function basically
both are same thing the method is a function that belong to an
object
Methods: Method is a Function that is available for a given
object because of the object type
that mean if I am taking a string so string has its own method
if I am taking List- List has it own method
and if I am taking a module
like if I am try to import math that means math will have their
own function and the function will have their own method
in short :Method is a function so if we are using string
String has it own method
Dictionary tuple they have their own specific method
strings have method associated with them dot .notation used for
method and used on string manipulation u have to refer method to
the particular string followed by dot and the method attributes such
as replace I can see this method using dir with its values passed in
parenthesis type help for method

dir(str) dir allows you to view built in method here string as a


example so we have so many built in methods strings
Note you can use dir in other built in objects integers float
dir functions is the great wat to check built in methods available for
python objects you can apply with the variable you created and can
check what you cando with that variab;e
>>> string = "Hello"
>>> dir(string)
String Method Exmaple
for an example let create two variable x and y
x=”hello worl”
y-‘HELLO WORLD’
so to use a method on a string or any variable all we have to do is
add a dot you can see a list of different type of method that are
available and this method helps u to format our string
here we capitalize a string
print(x.capitalize)
print(y.capitalize)
remember whenever we use any method or function it must be
followed by opening and closing parenthesis after that particular
keyword
so after using this particular method it capitalize for both the string
that is first letter are change to capital and rest are small
so if I have a paragraph lot more string yu can easily format that
paragraph with the help of this method
Turning a String to lower case or upper case by
using:-lower method # running lower method on the string to lower case
str.lower()#using lower keyword
upper method# using upper method to uppercase
str.upper()#upper keyword
NOTE:! although we applied the lower and upper method
on the string you can check the variable str it still in its
original format same string in its own case this shows that
string are immutable
title method
Another Example:
#sh ip int brief command on cisco device
#show interfaces in Sentence Case
# way the info of interfaces displayed are varied from Vendor to Vendors
#converting sentence case to lower case
intf = 'GigabitEthernet0/0'

print(intf)
print(intf.lower())
print(intf)#int stores original value
print("---------------------------")
print(intf.upper())
print(intf)#int stores original value

print("---------------------------")
#result stored in other variable
intlower =intf.lower()
print(intlower)
print("---------------------------")
intup =intf.upper()
print(intup)
print("---------------------------")
print(intf)
print(intlower)
print(intup)

print("inverted commas not showed in print stmt\n but it will show in


interactive terminal mode")
----------------------------------------------------
Count Method
How many Time character appear in a string or generally
speaking an elements within a sequence by using the count
function
count method # count certain number of strings appears
#Strings - character count the syntax is similar to index
function by using the variable name followed by dot notaion
and then count open parenthesis and target letter for number of
count in close parenthesis
str.count=("H") #returns 1 we have one h in hello world
you can also verify that the string starts and ends with particular
character we have two method for this they are startwith and ends
with method
-------------------------------------------------------------
Count Another Example
print("Count Returns Integer Values of number of ocurences\nof the
value that you are searching for ")
str1 ="10.1.1.12"
print(str1.count('1'))# number of 1 in the string
print(str1.count('.'))# number of DOTS in the string
print(str1.count('2'))# number of DOTS in the string
print(str1.count('10'))# number of TEN in the string
print(str1.count('0'))# number of ZERO in the string
print("-----------------------")
octet = "11000000"
print(octet.count('1'))#how many 1 octet contains
print(octet.count('0'))#how many 0 octet contains
print("-----------------------")
octet1 ="1110000"
print(octet1.count('1'))#how many 1 octet1 contains
print(octet1.count('0'))#how many 0 octet1 contains

print("-----------------------")
print(octet1.count('1') + octet1.count('0'))
check8 =(octet1.count('1') + octet1.count('0'))

print(check8)

if check8 < 8:
print("Mistake")
print("------COUNT METHOD ALSO APPLY ON STRING --------
---------")
str2 ="It,is a \"Good Day\""
print(str2)
print(str2.count('o'))#howm many o are there in the string
print(str2.count('a'))#howm many a are there in the string
print(str2.count('d'))#howm many d are there in the string
print(str2.count(','))#howm many commas are there in the string
print(str2.count('Day'))#howm many instances of Day are there in
the string
StartsWith EndsWith Method
str.startswith("H")#return True
str.endswith("d")#return True on the same Logic and if it shows False
that particular is not available in that sequence of string
Example:
print("Useful when looking for values")
#such as looking for an ipaddress in as string
# string is a series of characters
#startswith values of characters
#and ends with characters
ipaddress ="10.1.2.3"
print('--------startsswith----------------')
print(ipaddress.startswith('10'))
#Boolean Object is returned
#is it True or False
print(ipaddress.startswith('1'))
#result True
print(ipaddress.startswith('1 0'))#starts with 1 space zero
#result False
print('--------Endswith----------------')
#result True
print(ipaddress.endswith('10'))
#result True
print(ipaddress.endswith('3'))#ends with 3
#result False
print('------------------------')
interface ="GigabitEthernet0/0"
print(interface.lower().startswith("gi"))#combine method in a single line
#result True
print(interface.lower().startswith("Gi"))#result False
print(interface)
print('------------------------')
print(interface.upper())
print(interface.upper().startswith("gi"))#result False
print(interface)
Important Method because we use them a lot
Strip Method
str.strip()#remove Whitespace
#eliminates all white spaces from the start and the end of the
string
let take an example we have three blank spaces
a= ' Cisco Switch '
lets apply the strip method which removes the spaces at th
beginning and the end of the string
a.strip()
now consider that instead of three spaces we have three $ sign
we want to remove
#removing a character from the beginning and the end of a string
split function takes one parameter and set where u want to split its creates
an array of item
c='$$$Cisco Router$$$'
eliminate the leading and trailing $ sign
so we have to specify the target character to eliminate in the strip method
enclosed in quotes
c.strip=('$') #remove a certain character
strstrip("$")#remove a certain character

Split Method- Split the Strings into sub string


-furthermore splitting a string by specifying a delimiter; the
result of this method is a list
d="Cisco, Avaya,Juniper,Nortel,HP"
d.split(",")
result by delimiter and in a lIst
[ "Cisco","Avaya","Juniper","Nortel","HP"]

Another Example
#on a switch or a Router when you use show command sh run
# ip address have spaces around them
#sh ip int brief have spaces
#strip method use to remove white space or other characters
from strings

ipvlan1 =' 192.168.122.72 '


print(ipvlan1)
print(ipvlan1.strip())#stripping all the spaces from both the
sides behind and front
ipvlan2 =' 192.168.122.72 '
print(ipvlan2.lstrip())#remove strip from left side
print(ipvlan2.rstrip())#remove strip from left side
print(ipvlan2.strip())#remove strip from left side

------------------------------------------------
splitlines method

isdigit
str1 = "10"
print(type(str1))
# can we check that this string variable contains number
#answer is yes we can
print(str1.isdigit())
#result Boolean True show integer digit are contained in the string

str2="h10"
print(type(str2))
print(str2.isdigit())

#result Boolean False show integer digit are not contained in the
string

check is upper

# take user input


# age = int(input("enter your age : ")) # strings
# print(age)
# take two user inputs
# user_name, age = input("enter your name and age : ").split(",")
# print(user_name)
# print(age)

JoinMethod
inserting a character in between every two characters of the
string / joining the characters by using a delimiter
" _".join(d)
Find and Replace Method
#Strings - finding a character or This method simply searches a
sequence of character inside the string and if find the match then it
returns the index where that sequence begins
str.find('hel")#0 we have a match starting at index 0
if didnt find a match and it wil return -1

Find and Replace Method# replace method takes to argument first


text which is to be replaced second desired text what we want to
replace second argument replace by comma
str.find("ello")
str.replace("","") #removing all occurrences of a character from a
string
""-indicates nothing
in first double quotes target and in second new comer element
Examples
# strings
name = "harshit"
# name[2] = "s"
print(name.replace("h","H",1))
print(name)

for example removing all kind of space from the string spaces

str=" pyt on Programming "


str.replace()#remove leading and trailing spaces including space in
between the string
Center Method
#Additional methods
#source:https://www.tutorialspoint.com/python3/python_strings.html
capitalize() #Capitalizes first letter of string.
lstrip() #Removes all leading whitespace in string.
rstrip() #Removes all trailing whitespace of string.
swapcase() #Inverts case for all letters in string.
title() #Returns "titlecased" version of string, that is,
all words begin with uppercase and the rest are
lowercase.
Questioning or Judging a string using is
isalnum() #Returns true if string has at least 1
character and all characters are alphanumeric and
false otherwise.
isalpha() #Returns true if string has at least 1
character and all characters are alphabetic and
false otherwise. isdigit() #Returns true if string
contains only digits and false otherwise. islower()
#Returns true if string has at least 1 cased
character and all cased characters are in
lowercase and false otherwise. isnumeric()
#Returns true if a unicode string contains only
numeric characters and false otherwise. isspace()
#Returns true if string contains only whitespace
characters and false otherwise. istitle() #Returns
true if string is properly "titlecased" and false
otherwise. isupper() #Returns true if string has at
least one cased character and all cased characters
are in uppercase and false otherwise. #source:
https://www.tutorialspoint.com/python3/python_stri
ngs.html
Index Method
Index of a character in a given string by using the index
function just remember it only returns the first occurrence of
that particular character
let's create a variable and assign it
a="Cisco Switch"
let's find out the index of the first i in the string so we pass the
name of a varaible followed by dot notation index function and
associated letter i in parenthesis enclosed in quotes
a.index('i')#returns 1 the index of first occurrence of i in the
string which is correct which is second letter in that string
--------------------------------

String Indexing-
this applies to other Data types also
Positioning / String Slicing
String is A Sequence Type meaning individual character
have a Index associated with them and you can reference
this index and Python uses indexes to keeps track or mark of
position of every element in string as a set of character
Another Explanation:
String is a sequence of element which means each element in a
string is a Data Value and it has a specific order so you can
actually index the letters in a string to grab Particular Letter,
pulling specific thing out of the String
In other words
It is helpful to think of a string as an Ordered Sequence of
characters or combination of individual characters e.g. Letters
Numbers spaces and Symbols :The idea of Sequence and Position
or order of a character in a string in Python is Important
For Example we have the String Python it's important for the P to
come before the Y T and so on otherwise letters are all Scrambled
up and we ended up with jumble
Another Explanation
Unlike the other data types you have seen so far, you can also index into
strings ,meaning Each element in the sequence can be accessed
Accessing the characters of a string by the array of numbers
u can accessed them using String indexing or String Positioning
# in Python String are indexed Like an Array
python makes an array or collection of characters
Every character has it position
The first element of a sequence when counting from left to right
its starts with 0 and the second element is index 1 so to fetch it u
have to use square brackets [] and passed the index value in
parenthesis when counting backwards its start from right to left the
first index will be minus one -1 indexing number because the first
left letter of a string is -1and the next letter from the right to left will
have index -2 and so on
Index are enclosed by square brackets whenever we want to access
some letters in the string
for two character u use colon between two index number
left one is start and the right one is up to and not including
it is up to in other word
first index is inclusive and last is not inclusive
# formula is if your string character length is 11 then the formula is
total length minus 1 so our index value is [0:12] to spit out the full
string passing two index start and stop
Start argument Stop Argument Step Argument

String Indexing Examples


Lets Start Indexing/Code Example
type variable str
str="Hello"#python understand string” Hello” to be a sequence of
Letters in a specific order this means we will be able to use
indexing to grab or extract particular letters
(like the first letter or last letter)
str.index("H")
always use square brackets to write index
str.index("H")
str[0] ]
# here we retrieve or Offset H from index 0 because Python find
first character type str the name of a variable and index zero
enclosed in square brackets so its Show first letter of the string
which happened to be H and its the first character of the string
Notice Python uses 0 indexing for string like many other languages
The Offset of the left character or The Index of the first character or the
first element is zero
Next Element find second character
str[1] ]#index 1
Next Element / Third Character of the String
str[2]#index 2
Note Forget Spaces Count as Character do
Extract More than one Character Using Range -
we also using range starting at the first posting or the second
character to the end by typing colon and square brackets
str[1:]
get all the first character of the string
or in simple way
String Slicing or Dice your String allows to cut it up or
extract certain parts of the string the general syntax for sting
slicing first we have a name of a variable
pointing to that string followed by square brackets in between the
bracket we have colon on the left side of the colon we specify the
index positioning to start the slice and after the colon slice upto
but not including to the right side of colon
varaiblename[start:upto]
We can use : to perform Slicing which grab everything up to a
Designated Point
str="Python Programming"
Starting Offset and Ending Offsets
str[1:5]#we start at index 1 and ends upto index 5 so we have
character index 1 index 2 index 3 index 4 will be considered for
this slice and so we get ytho as a result
if we dont specify the second in the brackets what would happen the
string slice start at argument given before the colon and would end
of the string
str[1:] # ython Programming Grab Everything Past the first
term all the way to the length of str
using python which is len(str)#len keyword
String Contain Length Information and the character with its
indexed value used for iterating in search process
getting the the length of the string using python built in
function
len function built in function that returns the length of an object or
the numbers of character in the string ie -string_length
=len("string_length")#counts every elements in the String including
spaces
print(string_length)

Wha we dont specify the first index before the colon and
specify only the second index
slice will simply start at the beginning of the string up to but not
including the second index
str[:3]#Pyt
Note the Above Slicing
Here we are telling Python to Grab Everything from 0 up to 3 it
doesn’t include the third index
You will notice this a lot in Python where statement are usually
in the context of up to but not including whatever the index is
What we dont enter any indexex all then entire string will be
return
str[:]#
Negative indexing- Using Negative value to
access the left character of the string
We can also use negative indexing with strings to go backwards of
the string
str[-1]#g is The last element is given by the index -1
str[-2]#this gives the next chracter when counting left to right and ie
second last-2
one index behind zero so its loop back around
The first element can be obtained by index
str[:-1]# grab everything but not the Last letter
Steps:
you can specify the third element within the square brackets
after the indexex also sepearated by colon this is called the step
We can also used index and Slice Notation to grab element of a
sequence by a specified step size the fault is 1
For Instance we can use two Colons in a row and then a
number specifying the frequency to grab element for Example
str[::1]# ]# grab everything but go in step size of 1
str[::2]# grab everything but go in step size of 2
str[::-1] ]# print a string backward
print in reverse order
Invalid Input Indexing
Note! String Index out of range when you provide an
index for which a list elements not present
let's try it
string1="Cisco Router"
# string indexing
# print(name[-1])
# string slicing
# print(name[-1:0:-1])

-----------------------------------------------------------------------------------------
#Slicing is really useful you can extract text from Router Config
# look for specific for text

str1= "Cisco IOSv Router"


print(str1)
print(str1[0])#first character lefthand side
#Use Square Bracket to Retrieve what called an offset
#left most character or first charactet which has an Offset of 0
# print out C

print(str1[1])
#Offset of 1 has a value of i

print(str1[2])
#Offset of 2 has a value of s
#it is the third character in the string

#work Backwards using Negative


print(str1[-1])#last character on the righthand side so gives r
print(str1[-2])#gives e
print(str1[-3])#gives t

print("--------------------------------")

#retreive spaces
#counting from right to left we have
print(str1[-7])#sapce retrive because it exist betweent thos two single quotes
#space is a character
print(str1[-8])
print("--------------------------------")
print(len(str1))#finds length of the character string1

print("------------out of ange Error--------------------")


#print(str1[20])#out of range error becs only 17 character exist in the string str1
#print(str1[18])#same with 18
#print(str1[17])#17 is offset so out of range doesnt work
print(str1[16])#16 is the seventeen character works
print("------------reverse order- lfet to right-------------------")
print(str1[-17])
#print(str1[-18])#range error

print("------------Slicing--------------------")

#slice and dice your string


#cut it up extract certain portion of the string
#slicing makes us very easy to slice of a string
#define slice using square brackets [si]
#slicing using starting offset and ending offsets s[i:j] slice of s from i to j
#s[i:j:k]slice of s from i to j with step k where k allows to skip characters
str1= "Cisco IOSv Router"
print(str1[:])#print whole value of str1
print(str1[10:])#Starting offset value from 10 till end gives space and router
print(str1[11:])#gives only router
print(str1[12:])#offsets of 12 gives outer

print(str1[11:13])#offsets start of 11 and to offsets of 13


#Ro
#this is the Start Offset R to the end offset minus by one

print("------------Negative Slicing--------------------")

print(str1[-3:])

print(str1[-6:])
print(str1[-3:])
print(str1[11:])

print("------------Going Backward--------------------")
print(str1[11:-3])#start from 11 and went one less minus3
print(str1[5:-3])
print(str1[5:-4])
print(str1[6:-4])#sapce not included

print("-------------------------------")
print(str1[:])
print(str1[1:-1])#start with an Offset of 1 and offset of -1

print("-------------------------------")
str2="Cisco IOSv Router"
print(str2)
print(len(str2))
print(str2[1:-1:2])#steps of 2
print("-------------------------------")
print(str2[1:-2:2])
print(str2[1:-5:2])
print("-------------------------------")
print(str2[::-1])
print(str2[:])
print("---------Rversal of Text----------------------")
print(str2[-1::-1])#starting at the end and refversing the text
print(str2[::-1])#same result
print(str2[-2::-1])
print(str2[-4::-1])
print(str2[-10::-1])

print(str2[20:])
print(str2[20:20])

print(str2[10:20])
print(len(str2[10:20]))
print(str2[10:10])

print("---------Rversal of Text 1----------------------")


print(str2[0:-1])
print(str2[0:])

print("---------Steps----------------------")
print(str2[::2])#step of 1
print(str2[::3])#step of 2

print(str2[:])
print(str2[::4])#step of 3

print(str2[::5])#step of 4
-----------------------------------------------------------------------------

Len Function
how do we get the length of the string using len function passing the variable
name as a method it will count how many character in the sring and returns the
numbers of character to us lets use the len function specify the varaible name in
betweent the parentheis
# len function
# print(len(name))
len(string1)# 12character (Space included because
space is a character)
so the last character is index 11
string1[11]#r which s equivalent to
string1[-1]#r same output
so what happened if we enter wrong index
string[20]#Lets read the error text the type of error
is Index Error: and it says String out of Range
Python finds out that we type invalid Index in
between the Square brackets and told us index is out
of range since we have 20 character of string and we
passed 20 which can't have position of 20 obviously
String Checking
#Strings - checking whether the string starts with a character
str.startswith("H")
#Strings - checking whether the string ends with a character
str.endswith("d")
# lower, upper, title method (converting the case)
str.lower()#lowercase
str.upper()#uppercase
# print(name.title())
# find, replace, center method
# r_pos = name.find("r")
# r_pos_2 = name.find("r", r_pos + 1)
# print(r_pos_2)
# **harshit**
# print(name.center(14, "*"))
# strings are immutable

You might also like