SlideShare a Scribd company logo
Strings
Team Emertxe
Strings And Characters
Strings And Characters
Creating Strings
Example-1 s = 'Welcome to Python'
Example-2 s = "Welcome to Python"
Example-3 s = """
Welcome to Python
"""
Example-4 s = '''
Welcome to Python
'''
Example-5 s = "Welcome to 'Core' Python"
Example-6 s = 'Welcome to "Core" Python'
Example-7 s = "Welcome totCorenPython"
Example-8 s = r"Welcome totCorenPython"
Strings And Characters
Length of a String
len() Is used to find the length of the string
Example str = "Core Python"
n = len(str)
print("Len: ", n)
Strings And Characters
Indexing the Strings
str = "Core Python"
#Method-1: Access each character using
while loop
n = len(str)
i = 0
while i < n:
print(str[i], end=' ')
i += 1
#Method-2: Using for loop
for i in str:
print(i, end=' ')
#Method-3: Using slicing operator
for i in str[::]:
print(i, end='')
print()
#Method-4: Using slicing operator
#Take sthe step size as -1
for i in str[: : -1]:
print(i, end='')

Both positive and Negative indexing is possible in Python
Strings And Characters
Slicing the Strings
str = "Core Python"
1 str[: :]
Prints all
2 str[0: 9: 1]
Access the string from 0th to 8th element
3 str[0: 9: 2]
Access the string in the step size of 2
4 str[2: 3: 1]
Access the string from 2nd to 3rd Character
5 str[: : 2] Access the entire string in the step size of 2
6 str[: 4: ] Access the string from 0th to 3rd location in steps of 1
7 str[-4: -1: ] Access from str[-4] to str[-2] from left to right
8 str[-6: :] Access from -6 till the end of the string
9 str[-1: -4: -1] When stepsize is negative, then the items are counted from right to
left
10 str[-1: : -1] Retrieve items from str[-1] till the first element from right to left
Strings And Characters
Repeating the Strings

The repetition operator * is used for repeating the strings
Example-1 str = "Core Python"
print(str * 2)
Example-2
print(str[5: 7] * 2)
Strings And Characters
Concatenation of Strings

+ is used as a concatenation operator
Example-1 s1 = "Core"
s2 = "Python"
s3 = s1 + s2
Strings And Characters
Membership Operator

We can check, if a string or a character is a member of another string or not using
'in' or 'not in' operator

'in' or 'not in' makes case sensitive comaprisons
Example-1 str = input("Enter the first string: ")
sub = input("Enter the second string: ")
if sub in str:
print(sub+" is found in main string")
else:
print(sub+" is not found in main string")
Strings And Characters
Removing Spaces
str = " Ram Ravi "
lstrip() #Removes spaces from the left side
print(str.lstrip())
rstrip() #Removes spaces from the right side
print(str.rstrip())
strip() #Removes spaces from the both sides
print(str.strip())
Strings And Characters
Finding the Sub-Strings

Methods useful for finding the strings in the main string

- find()

- rfind()

- index()

- rindex()

find(), index() will search for the sub-string from the begining

rfind(), rindex() will search for the sub-string from the end

find(): Returns -1, if sub-string is not found

index(): Returns 'ValueError' if the sub-string is not found
Strings And Characters
Finding the Sub-Strings
Syntax mainstring.find(substring, beg, end)
Example str = input("Enter the main string:")
sub = input("Enter the sub string:")
#Search for the sub-string
n = str.find(sub, 0, len(str))
if n == -1:
print("Sub string not found")
else:
print("Sub string found @: ", n + 1)
Strings And Characters
Finding the Sub-Strings
Syntax mainstring.index(substring, beg, end)
Example str = input("Enter the main string:")
sub = input("Enter the sub string:")
#Search for the sub-string
try:
#Search for the sub-string
n = str.index(sub, 0, len(str))
except ValueError:
print("Sub string not found")
else:
print("Sub string found @: ", n + 1)
Strings And Characters
Finding the Sub-Strings: Exercise
1 To display all positions of a sub-string in a given main string
Strings And Characters
Counting Sub-Strings in a String
count() To count the number of occurrences of a sub-string in a main string
Syntax stringname.count(substring, beg, end)
Example-1 str = “New Delhi”
n = str.count(‘Delhi’)
Example-2 str = “New Delhi”
n = str.count(‘e’, 0, 3)
Example-3 str = “New Delhi”
n = str.count(‘e’, 0, len(str))
Strings And Characters
Strings are Immutable

Immutable object is an object whose content cannot be changed
Immutable Numbers, Strings, Tuples
Mutable Lists, Sets, Dictionaries
Reasons: Why strings are made immutable in Python
Performance Takes less time to allocate the memory for the Immutable objects, since
their memory size is fixed
Security Any attempt to modify the string will lead to the creation of new object in
memory and hence ID changes which can be tracked easily
Strings And Characters
Strings are Immutable

Immutable object is an object whose content cannot be changed

Example:

s1 = “one”

s2 = “two”

S2 = s1
one two
S1 S2
one two
S1 S2
Strings And Characters
Replacing String with another String
replace() To replace the sub-string with another sub-string
Syntax stringname.replace(old, new)
Example str = "Ram is good boy"
str1 = str.replace("good", "handsome")
print(str1)
Strings And Characters
Splitting And Joining Strings
join() - Groups into one sring
Syntax separator.join(str)
- separator: Represents the character to be used between two strings
- str: Represents tuple or list of strings
Example str = ("one", "two", "three")
str1 = "-".join(str)
split() - Used to brake the strings
- Pieces are returned as a list
Syntax stringname.split(‘character’)
Example str = "one,two,three"
lst = str.split(',')
Strings And Characters
Changing the Case of the Strings
Methods upper()
lower()
swapcase()
title()
str = "Python is the future"
upper() print(str.upper()) PYTHON IS THE FUTURE
lower() print(str.lower()) python is the future
swapcase() print(str.swapcase()) pYTHON IS THE FUTURE
title() print(str.title()) Python Is The Future
Strings And Characters
Check: Starting & Ending of Strings
Methods startswith()
endswith()
str = "This is a Python"
startswith() print(str.startswith("This")) True
endswith() print(str.endswith("This")) False
Strings And Characters
String Testing Methods
isalnum() Returns True, if all characters in the string are alphanumeric(A – Z, a – z, 0
– 9) and there is atleast one character
isalpha() Returns True, if the string has atleast one character and all characters are
alphabets(A - Z, a – z)
isdigit() Returns True if the string contains only numeric digits(0-9) and False
otherwise
islower() Returns True if the string contains at least one letter and all characters are
in lower case; otherwise it returns False
isupper() Returns True if the string contains at least one letter and all characters are
in upper case; otherwise it returns False
istitle() Returns True if each word of the string starts with a capital letter and there
at least one character in the string; otherwise it returns False
isspace() Returns True if the string contains only spaces; otherwise, it returns False
Strings And Characters
Formatting the strings
format() Presenting the string in the clearly understandable manner
Syntax
"format string with replacement fields". format(values)
id = 10
name = "Ram"
sal = 19000.45
print("{}, {}, {}". format(id, name, sal))
print("{}-{}-{}". format(id, name, sal))
print("ID: {0}tName: {1}tSal: {2}n". format(id, name, sal))
print("ID: {2}tName: {0}tSal: {1}n". format(id, name, sal))
print("ID: {two}tName: {zero}tSal: {one}n". format(zero=id, one=name, two=sal))
print("ID: {:d}tName: {:s}tSal: {:10.2f}n". format(id, name, sal))
Strings And Characters
Formatting the strings
format() Presenting the string in the clearly understandable manner
Syntax
"format string with replacement fields". format(values)
n = 5000
print("{:*>15d}". format(num))
print("{:*^15d}". format(num))
Strings And Characters
Exercise
1. To know the type of character entered by the user
2. To sort the strings in alphabetical order
3. To search for the position for a string in agiven group of strings
4. To find the number of words in a given strings
5. To insert the sub-string into a main string in a particular position
THANK YOU

More Related Content

What's hot

Python for loop
Python for loopPython for loop
Python for loop
Aishwarya Deshmukh
 
List in Python
List in PythonList in Python
List in Python
Siddique Ibrahim
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
Praveen M Jigajinni
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
 
Data types in python
Data types in pythonData types in python
Data types in python
RaginiJain21
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
DPS Ranipur Haridwar UK
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
Sumit Satam
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
Mohd Sajjad
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
janani thirupathi
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
nitamhaske
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Mohammed Sikander
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
PyData
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
Pooja B S
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
Neeru Mittal
 
Python strings
Python stringsPython strings
Python strings
Mohammed Sikander
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 

What's hot (20)

Python for loop
Python for loopPython for loop
Python for loop
 
List in Python
List in PythonList in Python
List in Python
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Python strings
Python stringsPython strings
Python strings
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 

Similar to Python programming : Strings

stringsinpython-181122100212.pdf
stringsinpython-181122100212.pdfstringsinpython-181122100212.pdf
stringsinpython-181122100212.pdf
paijitk
 
Python data handling
Python data handlingPython data handling
Python data handling
Prof. Dr. K. Adisesha
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
Mr. Vikram Singh Slathia
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
strings11.pdf
strings11.pdfstrings11.pdf
strings11.pdf
TARUNKUMAR845504
 
Python ds
Python dsPython ds
Strings.ppt
Strings.pptStrings.ppt
Strings.ppt
SanthiyaAK
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
adityakumawat625
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
PadreBhoj
 
Strings part2
Strings part2Strings part2
Strings part2
yndaravind
 
String notes
String notesString notes
String notes
Prasadu Peddi
 
Implementation Of String Functions In C
Implementation Of String Functions In CImplementation Of String Functions In C
Implementation Of String Functions In C
Fazila Sadia
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
M Vishnuvardhan Reddy
 
Basic python part 1
Basic python part 1Basic python part 1
Basic python part 1
National University of Malaysia
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
omprakashmeena48
 
Unitii string
Unitii stringUnitii string
Unitii string
Sowri Rajan
 
regex.pptx
regex.pptxregex.pptx
regex.pptx
qnuslv
 
varthini python .pptx
varthini python .pptxvarthini python .pptx
varthini python .pptx
MJeyavarthini
 

Similar to Python programming : Strings (20)

stringsinpython-181122100212.pdf
stringsinpython-181122100212.pdfstringsinpython-181122100212.pdf
stringsinpython-181122100212.pdf
 
Python data handling
Python data handlingPython data handling
Python data handling
 
Python revision tour II
Python revision tour IIPython revision tour II
Python revision tour II
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
strings11.pdf
strings11.pdfstrings11.pdf
strings11.pdf
 
Python ds
Python dsPython ds
Python ds
 
Strings.ppt
Strings.pptStrings.ppt
Strings.ppt
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
 
Team 1
Team 1Team 1
Team 1
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
unit-4 regular expression.pptx
unit-4 regular expression.pptxunit-4 regular expression.pptx
unit-4 regular expression.pptx
 
Strings part2
Strings part2Strings part2
Strings part2
 
String notes
String notesString notes
String notes
 
Implementation Of String Functions In C
Implementation Of String Functions In CImplementation Of String Functions In C
Implementation Of String Functions In C
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
 
Basic python part 1
Basic python part 1Basic python part 1
Basic python part 1
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
Unitii string
Unitii stringUnitii string
Unitii string
 
regex.pptx
regex.pptxregex.pptx
regex.pptx
 
varthini python .pptx
varthini python .pptxvarthini python .pptx
varthini python .pptx
 

More from Emertxe Information Technologies Pvt Ltd

Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
Emertxe Information Technologies Pvt Ltd
 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf

More from Emertxe Information Technologies Pvt Ltd (20)

premium post (1).pdf
premium post (1).pdfpremium post (1).pdf
premium post (1).pdf
 
Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf
10_isxdigit.pdf
 
01_student_record.pdf
01_student_record.pdf01_student_record.pdf
01_student_record.pdf
 
02_swap.pdf
02_swap.pdf02_swap.pdf
02_swap.pdf
 
01_sizeof.pdf
01_sizeof.pdf01_sizeof.pdf
01_sizeof.pdf
 
07_product_matrix.pdf
07_product_matrix.pdf07_product_matrix.pdf
07_product_matrix.pdf
 
06_sort_names.pdf
06_sort_names.pdf06_sort_names.pdf
06_sort_names.pdf
 
05_fragments.pdf
05_fragments.pdf05_fragments.pdf
05_fragments.pdf
 
04_magic_square.pdf
04_magic_square.pdf04_magic_square.pdf
04_magic_square.pdf
 
03_endianess.pdf
03_endianess.pdf03_endianess.pdf
03_endianess.pdf
 
02_variance.pdf
02_variance.pdf02_variance.pdf
02_variance.pdf
 
01_memory_manager.pdf
01_memory_manager.pdf01_memory_manager.pdf
01_memory_manager.pdf
 
09_nrps.pdf
09_nrps.pdf09_nrps.pdf
09_nrps.pdf
 
11_pangram.pdf
11_pangram.pdf11_pangram.pdf
11_pangram.pdf
 
10_combinations.pdf
10_combinations.pdf10_combinations.pdf
10_combinations.pdf
 
08_squeeze.pdf
08_squeeze.pdf08_squeeze.pdf
08_squeeze.pdf
 
07_strtok.pdf
07_strtok.pdf07_strtok.pdf
07_strtok.pdf
 
06_reverserec.pdf
06_reverserec.pdf06_reverserec.pdf
06_reverserec.pdf
 
05_reverseiter.pdf
05_reverseiter.pdf05_reverseiter.pdf
05_reverseiter.pdf
 

Recently uploaded

Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 

Recently uploaded (20)

Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 

Python programming : Strings

  • 3. Strings And Characters Creating Strings Example-1 s = 'Welcome to Python' Example-2 s = "Welcome to Python" Example-3 s = """ Welcome to Python """ Example-4 s = ''' Welcome to Python ''' Example-5 s = "Welcome to 'Core' Python" Example-6 s = 'Welcome to "Core" Python' Example-7 s = "Welcome totCorenPython" Example-8 s = r"Welcome totCorenPython"
  • 4. Strings And Characters Length of a String len() Is used to find the length of the string Example str = "Core Python" n = len(str) print("Len: ", n)
  • 5. Strings And Characters Indexing the Strings str = "Core Python" #Method-1: Access each character using while loop n = len(str) i = 0 while i < n: print(str[i], end=' ') i += 1 #Method-2: Using for loop for i in str: print(i, end=' ') #Method-3: Using slicing operator for i in str[::]: print(i, end='') print() #Method-4: Using slicing operator #Take sthe step size as -1 for i in str[: : -1]: print(i, end='')  Both positive and Negative indexing is possible in Python
  • 6. Strings And Characters Slicing the Strings str = "Core Python" 1 str[: :] Prints all 2 str[0: 9: 1] Access the string from 0th to 8th element 3 str[0: 9: 2] Access the string in the step size of 2 4 str[2: 3: 1] Access the string from 2nd to 3rd Character 5 str[: : 2] Access the entire string in the step size of 2 6 str[: 4: ] Access the string from 0th to 3rd location in steps of 1 7 str[-4: -1: ] Access from str[-4] to str[-2] from left to right 8 str[-6: :] Access from -6 till the end of the string 9 str[-1: -4: -1] When stepsize is negative, then the items are counted from right to left 10 str[-1: : -1] Retrieve items from str[-1] till the first element from right to left
  • 7. Strings And Characters Repeating the Strings  The repetition operator * is used for repeating the strings Example-1 str = "Core Python" print(str * 2) Example-2 print(str[5: 7] * 2)
  • 8. Strings And Characters Concatenation of Strings  + is used as a concatenation operator Example-1 s1 = "Core" s2 = "Python" s3 = s1 + s2
  • 9. Strings And Characters Membership Operator  We can check, if a string or a character is a member of another string or not using 'in' or 'not in' operator  'in' or 'not in' makes case sensitive comaprisons Example-1 str = input("Enter the first string: ") sub = input("Enter the second string: ") if sub in str: print(sub+" is found in main string") else: print(sub+" is not found in main string")
  • 10. Strings And Characters Removing Spaces str = " Ram Ravi " lstrip() #Removes spaces from the left side print(str.lstrip()) rstrip() #Removes spaces from the right side print(str.rstrip()) strip() #Removes spaces from the both sides print(str.strip())
  • 11. Strings And Characters Finding the Sub-Strings  Methods useful for finding the strings in the main string  - find()  - rfind()  - index()  - rindex()  find(), index() will search for the sub-string from the begining  rfind(), rindex() will search for the sub-string from the end  find(): Returns -1, if sub-string is not found  index(): Returns 'ValueError' if the sub-string is not found
  • 12. Strings And Characters Finding the Sub-Strings Syntax mainstring.find(substring, beg, end) Example str = input("Enter the main string:") sub = input("Enter the sub string:") #Search for the sub-string n = str.find(sub, 0, len(str)) if n == -1: print("Sub string not found") else: print("Sub string found @: ", n + 1)
  • 13. Strings And Characters Finding the Sub-Strings Syntax mainstring.index(substring, beg, end) Example str = input("Enter the main string:") sub = input("Enter the sub string:") #Search for the sub-string try: #Search for the sub-string n = str.index(sub, 0, len(str)) except ValueError: print("Sub string not found") else: print("Sub string found @: ", n + 1)
  • 14. Strings And Characters Finding the Sub-Strings: Exercise 1 To display all positions of a sub-string in a given main string
  • 15. Strings And Characters Counting Sub-Strings in a String count() To count the number of occurrences of a sub-string in a main string Syntax stringname.count(substring, beg, end) Example-1 str = “New Delhi” n = str.count(‘Delhi’) Example-2 str = “New Delhi” n = str.count(‘e’, 0, 3) Example-3 str = “New Delhi” n = str.count(‘e’, 0, len(str))
  • 16. Strings And Characters Strings are Immutable  Immutable object is an object whose content cannot be changed Immutable Numbers, Strings, Tuples Mutable Lists, Sets, Dictionaries Reasons: Why strings are made immutable in Python Performance Takes less time to allocate the memory for the Immutable objects, since their memory size is fixed Security Any attempt to modify the string will lead to the creation of new object in memory and hence ID changes which can be tracked easily
  • 17. Strings And Characters Strings are Immutable  Immutable object is an object whose content cannot be changed  Example:  s1 = “one”  s2 = “two”  S2 = s1 one two S1 S2 one two S1 S2
  • 18. Strings And Characters Replacing String with another String replace() To replace the sub-string with another sub-string Syntax stringname.replace(old, new) Example str = "Ram is good boy" str1 = str.replace("good", "handsome") print(str1)
  • 19. Strings And Characters Splitting And Joining Strings join() - Groups into one sring Syntax separator.join(str) - separator: Represents the character to be used between two strings - str: Represents tuple or list of strings Example str = ("one", "two", "three") str1 = "-".join(str) split() - Used to brake the strings - Pieces are returned as a list Syntax stringname.split(‘character’) Example str = "one,two,three" lst = str.split(',')
  • 20. Strings And Characters Changing the Case of the Strings Methods upper() lower() swapcase() title() str = "Python is the future" upper() print(str.upper()) PYTHON IS THE FUTURE lower() print(str.lower()) python is the future swapcase() print(str.swapcase()) pYTHON IS THE FUTURE title() print(str.title()) Python Is The Future
  • 21. Strings And Characters Check: Starting & Ending of Strings Methods startswith() endswith() str = "This is a Python" startswith() print(str.startswith("This")) True endswith() print(str.endswith("This")) False
  • 22. Strings And Characters String Testing Methods isalnum() Returns True, if all characters in the string are alphanumeric(A – Z, a – z, 0 – 9) and there is atleast one character isalpha() Returns True, if the string has atleast one character and all characters are alphabets(A - Z, a – z) isdigit() Returns True if the string contains only numeric digits(0-9) and False otherwise islower() Returns True if the string contains at least one letter and all characters are in lower case; otherwise it returns False isupper() Returns True if the string contains at least one letter and all characters are in upper case; otherwise it returns False istitle() Returns True if each word of the string starts with a capital letter and there at least one character in the string; otherwise it returns False isspace() Returns True if the string contains only spaces; otherwise, it returns False
  • 23. Strings And Characters Formatting the strings format() Presenting the string in the clearly understandable manner Syntax "format string with replacement fields". format(values) id = 10 name = "Ram" sal = 19000.45 print("{}, {}, {}". format(id, name, sal)) print("{}-{}-{}". format(id, name, sal)) print("ID: {0}tName: {1}tSal: {2}n". format(id, name, sal)) print("ID: {2}tName: {0}tSal: {1}n". format(id, name, sal)) print("ID: {two}tName: {zero}tSal: {one}n". format(zero=id, one=name, two=sal)) print("ID: {:d}tName: {:s}tSal: {:10.2f}n". format(id, name, sal))
  • 24. Strings And Characters Formatting the strings format() Presenting the string in the clearly understandable manner Syntax "format string with replacement fields". format(values) n = 5000 print("{:*>15d}". format(num)) print("{:*^15d}". format(num))
  • 25. Strings And Characters Exercise 1. To know the type of character entered by the user 2. To sort the strings in alphabetical order 3. To search for the position for a string in agiven group of strings 4. To find the number of words in a given strings 5. To insert the sub-string into a main string in a particular position