This document provides an introduction and overview of strings in Python. It discusses that strings are a data type that can contain sequences of characters. The built-in string class is 'str' and strings can be defined using single, double, or triple quotes. Strings support various methods like indexing, slicing, concatenation, formatting and more. Common string methods are also described such as upper(), lower(), split(), join() which allow manipulating strings. The document also discusses comparing and slicing strings in Python.
This is presentation, that covers all the important topics related to strings in python. It covers storing, slicing, format, concatenation, modification, escape characters and string methods.
The file attatched also includes examples related to the slides shown.
String literals in python are surrounded by either single quotation marks, or double quotation marks. Strings can be output to screen using the print function. For example: print("hello"). Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
Variables & Data Types In Python | EdurekaEdureka!
YouTube Link: https://youtu.be/6yrsX752CWk
(** Python Certification Training: https://www.edureka.co/python **)
This Edureka PPT on 'Variables and Data Types in Python' will help you establish a foothold on Python by helping you learn basic concepts like variables and data types. Below are the topics covered in this PPT:
Introduction To Python
Applications Of Python
Variable Declaration
Variable Data Types
Type Conversion
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
All data values in Python are encapsulated in relevant object classes. Everything in Python is an object and every object has an identity, a type, and a value. Like another object-oriented language such as Java or C++, there are several data types which are built into Python. Extension modules which are written in C, Java, or other languages can define additional types.
To determine a variable's type in Python you can use the type() function. The value of some objects can be changed. Objects whose value can be changed are called mutable and objects whose value is unchangeable (once they are created) are called immutable.
This is presentation, that covers all the important topics related to strings in python. It covers storing, slicing, format, concatenation, modification, escape characters and string methods.
The file attatched also includes examples related to the slides shown.
String literals in python are surrounded by either single quotation marks, or double quotation marks. Strings can be output to screen using the print function. For example: print("hello"). Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
Variables & Data Types In Python | EdurekaEdureka!
YouTube Link: https://youtu.be/6yrsX752CWk
(** Python Certification Training: https://www.edureka.co/python **)
This Edureka PPT on 'Variables and Data Types in Python' will help you establish a foothold on Python by helping you learn basic concepts like variables and data types. Below are the topics covered in this PPT:
Introduction To Python
Applications Of Python
Variable Declaration
Variable Data Types
Type Conversion
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
All data values in Python are encapsulated in relevant object classes. Everything in Python is an object and every object has an identity, a type, and a value. Like another object-oriented language such as Java or C++, there are several data types which are built into Python. Extension modules which are written in C, Java, or other languages can define additional types.
To determine a variable's type in Python you can use the type() function. The value of some objects can be changed. Objects whose value can be changed are called mutable and objects whose value is unchangeable (once they are created) are called immutable.
OOPS concepts are one of the most important concepts in high level languages. Here in this PPT we will learn more about Object oriented approach in python programming which includes details related to classes and objects, inheritance, dat abstraction, polymorphism and many more with examples and code.
After the end of lesson you will be able to learn Python basics-What Python is? Its releases. Where we can use Python? Python Features. Tokens, comments variables etc... In out next PPT you will learn how to input and get output in Python
This presentation provides the information on python including the topics Python features, applications, variables and operators in python, control statements, numbers, strings, print formatting, list and list comprehension, dictionaries, tuples, files, sets, boolean, mehtods and functions, lambda expressions and a sample project using Python.
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
02 of 03 parts
Get Part 1 from https://www.slideshare.net/ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-1
Get Part 3 from https://www.slideshare.net/ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-3
C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to PLCs and embedded system.
OOPS concepts are one of the most important concepts in high level languages. Here in this PPT we will learn more about Object oriented approach in python programming which includes details related to classes and objects, inheritance, dat abstraction, polymorphism and many more with examples and code.
After the end of lesson you will be able to learn Python basics-What Python is? Its releases. Where we can use Python? Python Features. Tokens, comments variables etc... In out next PPT you will learn how to input and get output in Python
This presentation provides the information on python including the topics Python features, applications, variables and operators in python, control statements, numbers, strings, print formatting, list and list comprehension, dictionaries, tuples, files, sets, boolean, mehtods and functions, lambda expressions and a sample project using Python.
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
02 of 03 parts
Get Part 1 from https://www.slideshare.net/ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-1
Get Part 3 from https://www.slideshare.net/ArunUmrao/notes-for-c-programming-for-bca-mca-b-sc-msc-be-amp-btech-1st-year-3
C is a general-purpose, procedural computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations. C provides constructs that map efficiently to typical machine instructions and has found lasting use in applications previously coded in assembly language. Such applications include operating systems and various application software for computers, from supercomputers to PLCs and embedded system.
• List is a collection, which is ordered and changeable. Allows duplicate members.
• Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
• Set is a collection, which is unordered and unindexed. No duplicate members.
• Dictionary is a collection, which is unordered, changeable and indexed. No duplicate members.
: String, List, Tuple, Dictionary
• List is a collection, which is ordered and changeable. Allows duplicate members.
• Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
• Set is a collection, which is unordered and unindexed. No duplicate members.
• Dictionary is a collection, which is unordered, changeable and indexed. No duplicate members.
About
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Technical Specifications
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
Key Features
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface
• Compatible with MAFI CCR system
• Copatiable with IDM8000 CCR
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
Application
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Hierarchical Digital Twin of a Naval Power SystemKerry Sado
A hierarchical digital twin of a Naval DC power system has been developed and experimentally verified. Similar to other state-of-the-art digital twins, this technology creates a digital replica of the physical system executed in real-time or faster, which can modify hardware controls. However, its advantage stems from distributing computational efforts by utilizing a hierarchical structure composed of lower-level digital twin blocks and a higher-level system digital twin. Each digital twin block is associated with a physical subsystem of the hardware and communicates with a singular system digital twin, which creates a system-level response. By extracting information from each level of the hierarchy, power system controls of the hardware were reconfigured autonomously. This hierarchical digital twin development offers several advantages over other digital twins, particularly in the field of naval power systems. The hierarchical structure allows for greater computational efficiency and scalability while the ability to autonomously reconfigure hardware controls offers increased flexibility and responsiveness. The hierarchical decomposition and models utilized were well aligned with the physical twin, as indicated by the maximum deviations between the developed digital twin hierarchy and the hardware.
Overview of the fundamental roles in Hydropower generation and the components involved in wider Electrical Engineering.
This paper presents the design and construction of hydroelectric dams from the hydrologist’s survey of the valley before construction, all aspects and involved disciplines, fluid dynamics, structural engineering, generation and mains frequency regulation to the very transmission of power through the network in the United Kingdom.
Author: Robbie Edward Sayers
Collaborators and co editors: Charlie Sims and Connor Healey.
(C) 2024 Robbie E. Sayers
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
CFD analysis is incredibly effective at solving mysteries and improving the performance of complex systems!
Here's a great example: At a large natural gas-fired power plant, where they use waste heat to generate steam and energy, they were puzzled that their boiler wasn't producing as much steam as expected.
R&R and Tetra Engineering Group Inc. were asked to solve the issue with reduced steam production.
An inspection had shown that a significant amount of hot flue gas was bypassing the boiler tubes, where the heat was supposed to be transferred.
R&R Consult conducted a CFD analysis, which revealed that 6.3% of the flue gas was bypassing the boiler tubes without transferring heat. The analysis also showed that the flue gas was instead being directed along the sides of the boiler and between the modules that were supposed to capture the heat. This was the cause of the reduced performance.
Based on our results, Tetra Engineering installed covering plates to reduce the bypass flow. This improved the boiler's performance and increased electricity production.
It is always satisfying when we can help solve complex challenges like this. Do your systems also need a check-up or optimization? Give us a call!
Work done in cooperation with James Malloy and David Moelling from Tetra Engineering.
More examples of our work https://www.r-r-consult.dk/en/cases-en/
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdffxintegritypublishin
Advancements in technology unveil a myriad of electrical and electronic breakthroughs geared towards efficiently harnessing limited resources to meet human energy demands. The optimization of hybrid solar PV panels and pumped hydro energy supply systems plays a pivotal role in utilizing natural resources effectively. This initiative not only benefits humanity but also fosters environmental sustainability. The study investigated the design optimization of these hybrid systems, focusing on understanding solar radiation patterns, identifying geographical influences on solar radiation, formulating a mathematical model for system optimization, and determining the optimal configuration of PV panels and pumped hydro storage. Through a comparative analysis approach and eight weeks of data collection, the study addressed key research questions related to solar radiation patterns and optimal system design. The findings highlighted regions with heightened solar radiation levels, showcasing substantial potential for power generation and emphasizing the system's efficiency. Optimizing system design significantly boosted power generation, promoted renewable energy utilization, and enhanced energy storage capacity. The study underscored the benefits of optimizing hybrid solar PV panels and pumped hydro energy supply systems for sustainable energy usage. Optimizing the design of solar PV panels and pumped hydro energy supply systems as examined across diverse climatic conditions in a developing country, not only enhances power generation but also improves the integration of renewable energy sources and boosts energy storage capacities, particularly beneficial for less economically prosperous regions. Additionally, the study provides valuable insights for advancing energy research in economically viable areas. Recommendations included conducting site-specific assessments, utilizing advanced modeling tools, implementing regular maintenance protocols, and enhancing communication among system components.
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
2. Ms.Mhaske N.R. (PPS) 2
Introduction
● String is a data type in python
● String is a sequence made up of one or more individual characters
● Where characters could be a letter, digit,whitespace or any other
symbol
● Python has inbuild class name 'str' that has many useful feature
● We can declare and define a string by creating a variable of string type.
● String literal can be enclosed by either triple, double,or single quotes.
● Escape sequence with each type of string literal
● E,g. name=”India”
● Graduate='B.E.'
3. Ms.Mhaske N.R. (PPS) 3
Reading and Converting
• We prefer to read data
in using strings and
then parse and convert
the data as we need
• This gives us more
control over error
situations and/or bad
user input
• Raw input numbers
must be converted
from strings
>>> name = raw_input('Enter:')
Enter:Chuck
>>> print name
Chuck
>>> apple = raw_input('Enter:')
Enter:100
>>> x = apple – 10
Traceback (most recent call last):
File "<stdin>", line 1, in
<module>TypeError: unsupported
operand type(s) for -: 'str' and 'int'
>>> x = int(apple) – 10
>>> print x
90
4. Indexing
• We can get at any single
character in a string using
an index specified in square
brackets
• The index value must be an
integer and starts at zero
• The index value can be an
expression that is computed
>>> fruit = 'banana'
>>> letter = fruit[1]
>>> print letter
a
>>> n = 3
>>> w = fruit[n - 1]
>>> print w
n
00
bb
11
aa
22
nn
33
aa
44
nn
55
aa
5. Traversing a string
● A string can be traversed by accessing characters from one index to another
● E,g.
message=”hello”
Index=0
for i in message:
print(“message[“ , index,” ] ”= ”, i)
index += 1
OUTPUT: message[0]=h
message[1]=e
message[2]=l
message[3]=l
message[4]=o
●
6. Concatinating,Appending and Multiplaying
strings
● Concatenate :means to join together
● '+' opeartor is used for concating purpose.
● The * operator can be used to repeat the string for a given number of
times.
str1 = 'Hello'
str2 ='World!'
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
OUTPUT:
tr1 + str2 = HelloWorld!
str1 * 3 = HelloHelloHello
7. ● Append a string :to add something at the end.
● In python you can add one string at the end of another string using the
' +=' operator
● E.g.
Str='hello'
name=raw_input(“n enter your name”)
str+=name
Str+=”.welcome to pune”
print(str)
Output:
enter your name:ashish
hello ashish.welcome to pune
8. ● Iterating Through String :Using for loop we can
iterate through a string. Here is an example to count
the number of 'l' in a string.
count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')
OUTPUT:
3 letters found
9. String Membership Test
● We can test if a sub string exists within a string or not, using the
keyword in
>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False
10. String are Immutable
● Python string are immutable
● That is once created they cannot be changed.
● Whenever you try to modify an existing string variable, a new string is
created.
● Every object in python is stored in memory .
● You can find out whether two varibles are referring to the same object or not
by using the id().
● The id() returns the memory address of that object.
● As both str1 and str2 points to same memory location, they both point to the
same object
11. str1=”Hello”
print (“str1 is “,str1)
print(“id of str1 is”, id(str1))
str2=”world”
print(“str2 is”,str2)
print(“id of str2 is”,id(str2))
str1+=str2
print(“str1 after modification”,str1)
print(“id of str1 is”, id(str1))
str3=str1
print(“str3 is”,str3)
Print( “id of str3 is”, id(str3)
Output:
Str1 is Hello
id of str1 is 45093344
Str2 is world
id of str1 is 45093312
str1 after modification: Helloworld
Id of str1 is 43861792
Str3 Helloworld
Id of str3 is 43861792
12. Escape characters and their meaning
Escape character Meaning
a Bell or alert
b backspace
n New line
t Horizontal tab space
v Vertical tab space
r Enter button
x Character x
Display single
13. ● Raw String to ignore escape sequence
● Sometimes we may wish to ignore the escape sequences inside a string. To
do this we can place r or R in front of the string. This will imply that it is a raw
string and any escape sequence inside it will be ignored.
>>> print("This is x61 ngood example")
This is a
good example
>>> print(r"This is x61 ngood example")
This is x61 ngood example
14. Python String Formatting
● Escape Sequence
●
If we want to print a text like -He said, "What's there?"- we can neither use single quote or double
quotes.
●
An escape sequence starts with a backslash and is interpreted differently. If we use single quote to
represent a string, all the single quotes inside the string must be escaped. Similar is the case with
double quotes.
# using triple quotes
print('''He said, "What's there?"''')
# escaping single quotes
print('He said, "What's there?"')
# escaping double quotes
print("He said, "What's there?"")
OUTPUT :He said, "What's there?"
He said, "What's there?"
He said, "What's there?"
15. Formating symbol
Format symbol Purpose
%c character
%d or %i Signed decimal integer
%s string
%u Unsigned decimal integer
%o Octal integer
%x or %X Hexadecimal integer
%e or %E Exponential notation
%f Floating point number
%g or %G Short number in floating point or
exponential notation.
16. ● The syntax for string formatting opeartion is:
“<format>” % (<Values>)
● The statement began with a format string consisting of a sequence of characters and
conversion specifications.
● Conversion specification start with a % opeartor and can appear anywhere within the
string.
● Following the format string is a % sign and the a set value ,one per conversion
specification , seperated by commas and enclosed in parathesis. If ther is single value
then parenthesis is optional.
● E,g,
name=”ashish”
Age=8
print(“name=%s and age=%d” %(name,age))
print(“name=%s and age=%d”m, %(“ankita”,6))
Output:
name=ashish and age=8
name=ankita and age=6
17. ● Formatting a string means presenting the string in a clearly understandable
manner.
● The format method is used to format the string
● This methos is used as
'formatstring with replacement field'.format(value)
● E.g. id=10, name='shankar' sal=20000
1) Str='{},{},{}'.format(id,name,sal)
print(str) #output=10,shankar,20000
2) Str='{} - {} - {}'.format(id,name,sal)
print(str) #output=10 – shankar – 20000
3 )Str='id={}n name={}n sal={}'.format(id,name,sal)
print(str) #output=
id=10
name=shankar
sal=20000
18. Built-in string methods and functions
● String are an example of python objects.
● An object is an entity that contains both data(the actual string
itself) as well as functions to manupulate that data.
● These functions are availble to any instance(variable) of the object
● Python supports many built-in methods.
● A methods is just like a function.
● The only difference between function and tring methods is invoked
or called on an object.
● e.g. if the varible str is a string, then you can call the upper()
methods as str.upper() to convert all the characters of str in
uppercase.
19. Python has a set of built-in methods that you can use on
strings.
/media/admin1/HP x740w/PPS PPT/UNIT iv/in built function in string.pdf
20. String methods
Function Usage Example
Capitalize() To capitalize first letter of the string str=“hello”
print(str.capitalize())
O: Hello
Center(width,fillchar) Returns string with the original string
centered to a total of width columns and filled
with fillchar in columns that do not have
characters
Str=“hello”
print(str.center(10,’*’))
O: **hello***
Count(str,beg,end) Counts number of times str occurs in a
string.
msg=“my best friend”
print(msg.endswith(“end”,0,
len(msg)))
O: True
Endswith(suffix,beg,end) Checks if string ends with prefix msg=“my best friend”
print(msg.endswith(“end”,0,
len(msg)))
O: True
startswith(suffix,beg,end) Checks if string starts with prefix msg=“my best friend”
print(msg.startswith(“my”,0,
len(msg)))
O: True
Find(str,beg,end) Checks if str is present in string. msg=“my best friend”
print(msg.find(“best”,0, len(msg)))
O: 3
Index(str, beg, end) Same as find but raises an exception if str
is not found
msg=“my best friend”
print(msg.index(“mine”,0,
len(msg)))
O: valuerror:substring not found
21. String methods
Function Usage Example
Rfind(str,beg,end) Same as find but starts searching from
the end
msg=“my best friend”
print(msg.rfind(“best”,0, len(msg))
O: 3
Rindex(str,beg,end) Same as index but starts searching from
the end and but raises an exception if
str is not found
msg=“my best friend”
print(msg.rindex(“my”,0, len(msg))
O: 0
Isalnum() Returns True if string has at least one
character and every character is either
a number or an alphabet
msg=“jamesbond007”
print(msg.isalnum())
O: True
Isalpha() Returns True if string has at least one
character and every character is an
alphabet
msg=“jamesbond007”
print(msg.isalpha())
O: False
Isdigit() Returns True if string contains only
digits
msg=“007”
print(msg.isdigit())
O: True
Islower() Returns True if string has at least one
character and every character is a
lowercase alphabet
msg=“Hello”
print(msg.islower())
O: False
Isspace() Returns True if string contains only
whitespace characters
msg=“ “
print(msg.isspace())
O: True
Isupper() Returns True if string has at least one
character and every character is a
uppercase alphabet
msg=“HELLO”
print(msg.isupper())
O: True
22. String methods
Format Usage Example
len(string) Returns the length of the string str=“hello”
print(len(str))
O : 5
ljust(width,[fillchar]) Returns a string left justified to a total of width columns. Columns
without characters are padded with the character specified in the
fillchar argument
str=“hello”
print(ljust(10,”’*’))
O : hello*****
rjust(width,[fillchar]) Returns a string right justified to a total of width columns.
Columns without characters are padded with the character
specified in the fillchar argument
str=“hello”
print(rjust(10,”’*’))
O : *****hello
zfill(width) Returns string left padded with zeros to a total of width
characters.
str=“1234”
Print(str.zfill(10))
O:0000001234
lower() Converts all characters in the string into lowercase str=“Hello”
print(str.lower())
O : hello
upper() Converts all characters in the string into uppercase str=“hello”
print(str.upper())
O : HELLO
lstrip() Removes all leading whitespace in string str=“hello”
print(lstr.lstrip())
O : hello
23. String methods
Format Usage Example
rstrip() Removes all trailing whitespace in string str=“hello ”
print(rstr.lstrip())
O : hello
strip() Removes all leading and trailing whitespace in string str=“ hello ”
print(str.lstrip())
O : hello
max(str) Returns the highest alphabetical character (having highest
ASCII value) from the string str
str=“hello friendz”
print(max(str))
O : z
min(str) Returns the lowest alphabetical character (having lowest ASCII
value) from the string str
str=“hello friendz”
print(min(str))
O : d
replace(old,new[,
max])
Replaces all or max occurrences of old in string with new str=“hello hello hello”
Print(str.replace(“he”,”fo”))
O:follo follo follo
title() Return string in title case str=“python language”
Print(str.title())
O: Python Language
swapcase() Toggles the case of every character str=“python Language”
Print(str.swapcase())
O: PYTHON lANGUAGE
24. String methods
FormatFormat UsageUsage ExampleExample
split(delim) Returns a list of substrings seperated by the
specified delimiter. If no delimiter is specified
then by default it spilts strings on all whiespace
characters
str=“abc,def,ghi,jkl”
print(str.split(,))
O: [‘abc’,’’def’,’ghi’,’jkl’]
join(list) Joins a list of strings using the delimiter with
which the function invoked.
print(‘-’.join([‘abc’,’def’,’gh
i’,’jkl’])
O:abc-def-ghi-jkl
isidentifier() Returns true if the string is a valid identifier str=“hello”
print(str.isidentifier())
O: True
enumerate(str) Returns an enumerate object that lists the
index and value of all the characters in the
string as pairs
str=“hello”
print(list(enumerate(str))
O: [(0,’h’),(1,’e’),(2,’l’),
(3,’l’),(4,’o’)]
25. Ord() and chr() functions
● Ord() : function returns the ASCII code of the
character
● Chr() :function returns character represented by
ASCII number.
● e.g.
ch=='R'
ptint(ord(ch))
Output: 82
Print (chr(82))
Output: R
26. Comparing string
● Python allows you to compare strings using relational (or comparison)
operator such as >,<.<=,>=, etc.
● ASCII value for A-Z is 65-90 and a-z is 97-122
Operator Description example
== If two strings are equal , it return
true
>>>”AbC”==”AbC”
True
!= or <> If two strings are not equal , it returns
true
>>”abC”!=”Abc”
True
> If the first string is greater than
second,it returns true
>>>”abc”>”Abc”
True
< If the second string is greater than
first,it returns true
>>>”abC”<”abc”
True
>= If the first string is greater than or equal
to the second,it return true
>>>”aBC”>=”ABC”
True
<= If the second string is greater than or
equal to the first,it return true
>>>”Abc”<=”ABc”
True
28. SLICE Operation
● A substring of a stirng is called a slice.
● The slice operation is used to refer to sub parts of sequence and
string
● You can take subset of a string from the original string by using [ ]
operator also known as slicing operator.
● e.g. string with indexing
29. ●
The syntax of slice opeartion is s[start:end]
● Where start specifies the beginning index of the substring and end-1 is the index of
the last chacters.
● Eg
str=”python”
print(“str[1:5]=”,str[1:5])
print(“str[:6]=”,str[:6])
print(“str[:]=”,str[:])
print(“str[1:20]=”,str[1:20])
● Output:
str[1:5]=ytho
Str[:6]=python
Str[:]=python
Str[1:20]=ython
31. Specifying stride while slicing strings
● In the slice operation , you can specify a third argument as the stride.
● Which refers to the number of characters to move forward after the first character is retrieved from the string.
● The default value of stride is 1.
str=”welcome to the world of python”
print(“str[2:10]=”,str[2:10])
print(“str[2:10:1]=”,str[2:10:1])
print(“str[2:10:2]=”,str[2:10:2])
print(“str[2:13:4]=”,str[2:13:4])
Output:
str[2:10]=lcome to
Str[2:10:1]=lcome to
Str[2:10:2]=loet
str[2:13:4]=le
32. ● Program to demonstrate slice opration with just
last(neagtive)argument.
● i.e print string in reverse order
str=”welcome to learn python:
print(“str[:-1]=”,str[::-1])
Output:
Str[:::-1]=nohtyp nrael ot emoclew
● Print[::-3]=nyr c
33. The string module
● The string module consists of a number of useful constant, classes and function.
● These functions are used to manipulate strings
●
String constant:some constant define in string modules are:
– string.ascii_letters:combination of ascii_lowercase and ascii_uppercase constant
– string.ascii_lowercase:refers to all lowercase letters from a-z
– string.ascii_uppercase:refers to all uppercase letters A-Z
– string.digit:refers to digit from 0-9
– string.hexdigit:refers to hexadecimal digit from 0-9,a-f and A-F
– string.lowercase:a string that has all the characters that are considered lowercase letters.
– string.octdigits:refers to octal,0-7
– string.punctuation:string of ASCII characters that are considered uppercase letter
– string.printable: string of printable characters which include digit,letter,punctucation, and whitespce.
– string.upperrcase:a string that has all the characters that are considered uppercase letters
– string.lowercase:a string that has all the characters that are considered lowercase letters
– string.whitespace:a string that all characters that are considerd whitespace like space, tab etc.
34. Str=”welcome to the world of python”
print(“uppercase=”,str.upper())
print(“lowercase=”,str.lower())
print(split=”,str.split())
print(“join =”,'-'.join(str.split()))
print(“replace=”,str.replace(“python”,”java”))
print(“count of o”,str.count('o'))
print(“find of=”,str.find(“of”))
Output:
Uppercase=WELCOME TO THE WORLD OFPYTHON
lowercse=welcome to the world of python
Split =['wlcome','to', 'the',' world', 'of', 'python']
join=welcome- to- the- world -of -python
Replace-welcome to the world of java
Count of o -5
Find of-21
35. String module
To see the content of string module, use dir() with the modulename.
>>>dir(string)
To know the details of perticuler item, you can use the type command.
e.g.
Import string
Print(type(string.digits))
OUTPUT:
<class ‘str’>.
import string
print(string.digits)
OUTPUT:
0123456789
Working with constants in string module
import string
print(‘g’ in string.lowercase)
OUTPUT:
True
36. Programming Examples
1.Write a program to print the follewing pattern
A
AB
ABC
ABCD
ABCDE
ABCDEF
2. Write a program that takes users name and PAN card number as
input.Validate the information using isX function and print the details.
.3. Write a program that encrypts a message by adding a key value to every
character
If key=3, then add 3 to every character
4. Write a program to reverse a string.