Python-strings
Python-strings
MODULE 2
STRINGS
Prof. Krishnananda L
Department of ECE
Govt Engineering College
Mosalehosahalli, Hassan
STRINGS:
Example 2 Example 3
Example1
INPUT: INPUT:
INPUT:
>>>a = 'Hello world’
>>>a = 'Hello world’
>>> print(‘Hello world’) >>>a[0]=‘M’
>>>print(a)
OUTPUT: OUTPUT:
OUTPUT:
Hello world Traceback (most recent call last):
Hello world File "<pyshell#19>", line 1, in
INPUT: <module>
INPUT:
>>> print(“Hello world@@”) a[0]='M'
>>>a = 'Hello world’
OUTPUT: TypeError: 'str' object does not
>>> a support item assignment
Hello world@@
OUTPUT: Note: String is “immutable” Not 3
possible to change the elements of the
‘Hello world’ string through assignment operator
POSITIVE AND NEGATIVE INDEXING OF A STRING:
4
MULTILINE STRINGS:
Normal:
With if statement: txt = "The quick brown fox jumps over
INPUT: the lazy dog!"
INPUT:
txt = ‘happiness is free“
txt = “happiness is free” if "fox" in txt:
print("free" in txt) print("Yes, 'fox' is present.")
if “free” in txt:
OUTPUT:
print("Yes, 'free' is present.") else:
True print ("No, ‘fox’ is not present")
OUTPUT:
INPUT:
Yes, 'free' is present.
txt = “happiness is free” ## to check for a phrase in a string
print(“hello” in txt)
>>>txt = "The best things in life are free!"
OUTPUT: >>>print(“life" in txt)
False True 9
CHECK STRING :
With if statement:
Normal:
INPUT:
INPUT:
txt = “welcome to python“
txt = ‘welcome to python’
if “hello" not in txt:
print(‘world’ not in txt)
print("Yes, ‘hello' is NOT present.")
OUTPUT:
OUTPUT:
True
Yes, ‘hello' is NOT present.
10
STRING LENGTH AND SLICING:
String length:
String slicing:
INPUT:
INPUT:
a = "Hello World”
b = "Hello World“
print(len(a))
print(b[2:5]) ## from index 2 to index4
OUTPUT:
OUTPUT:
11
llo
INPUT:
INPUT:
a = “Welcome to Python programming @@@“
b = "Hello World“
print (len(a))
print(b[:5]) ## from beginning 5 characters
OUTPUT:
OUTPUT:
33 11
Hello
STRING SLICING METHODS:
## illustration of slicing
## get a range of characters from the complete string ### Negative indexing
>>> a = " hello and welcome” >>>print(a.split(‘,’)) >>> a = " Hello World "
>>>print(a.strip())
>>>print(a.split()) OUTPUT:
OUTPUT:
OUTPUT: ['hello', 'how', 'are', 'you']
Hello World
['hello', 'and', 'welcome'] ## list with 4 elements
## remove white spaces at the
#list with 3 elements ## splits the string at the specified beginning and end of the string
separator and returns a list. Default
>>>a = " hello,how,are,you” separator white space >>> a = " our first python prog"
>>>print(a.lstrip(‘our’))
>>>print(a.split()) >>>a = “but put cut”
OUTPUT: OUTPUT:
>>>print(a.split(‘t’))
['hello,how,are,you'] first python prog 15
OUTPUT:
## list with single element ['bu', ' pu', ' cu', '']
BUILT-IN STRING METHODS IN PYTHON
True False
6
BUILT-IN STRING METHODS IN PYTHON
Hello,World
LOOPING TO COUNT:
INPUT:
INPUT:
s = "peanut butter“
word='python program’
count = 0
count=0
for char in s:
for letter in word:
if char == "t":
if letter=='p’:
count = count + 1
count=count+1
print(count)
print(count)
OUTPUT:
OUTPUT:
3
2 18
PARSING AND FORMAT STRINGS:
Parsing:
INPUT: Format:
st="From mamatha.a@gmail.com" INPUT:
pos=st.find('@’) print ('My name is %s and age is %d ’ % (‘Arun', 21))
print('Position of @ is', pos) OUTPUT:
OUTPUT: My name is Arun and age is 21
Position of @ is 14
19
STRING FORMATTING
20
MULTIPLE PLACE HOLDERS IN STRING FORMAT
INPUT: INPUT:
quantity = 3 quantity = 3
itemno = 5 itemno = 5
myorder = “I want {} pieces of item {} for {} myorder = "I want to pay {2} dollars for {0}
dollars.“ pieces of item {1}.“
OUTPUT: OUTPUT:
I want 3 pieces of item 5 for 49.95 dollars. I want to pay 49.95 dollars for 3 pieces of item 5.21
ESCAPE SEQUENCES
25
SUMMARY OF BUILT-IN STRING METHODS:
Method Description
find() Searches the string for a specified value and
capitalize() Converts the first character returns the position of where it was found
to upper case
format() Formats specified values in a string
casefold() Converts string into lower
case format_map() Formats specified values in a string
center() Returns a centered string index() Searches the string for a specified value and
Returns the number of returns the position of where it was found
count()
times a specified value isalnum() Returns True if all characters in the string are
occurs in a string alphanumeric
encode() Returns an encoded isalpha() Returns True if all characters in the string are
version of the string in the alphabet
endswith() Returns true if the string isdecimal() 26
Returns True if all characters in the string are
ends with the specified decimals
value
CONTD..
isdigit() Returns True if all characters in the string isupper() Returns True if all characters in the
are digits string are upper case
isidentifi Returns True if the string is an identifier join() Joins the elements of an iterable to the end
er() of the string
islower() Returns True if all characters in the string ljust() Returns a left justified version of the string
are lower case
isnumeri Returns True if all characters in the string lower() Converts a string into lower case
c() are numeric
lstrip() Returns a left trim version of the string
isprintab Returns True if all characters in the string
le() are printable maketrans() Returns a translation table to be used in
isspace() Returns True if all characters in the string translations
27
are whitespaces
istitle() Returns True if the string follows the
CONTD..
partition() Returns a tuple where the string is parted
into three parts rsplit() Splits the string at the specified
separator, and returns a list
replace() Returns a string where a specified value is
replaced with a specified value rstrip() Returns a right trim version of the
string
rfind() Searches the string for a specified value
and returns the last position of where it split() Splits the string at the specified
was found separator, and returns a list
rindex() Searches the string for a specified value splitlines() Splits the string at line breaks and
and returns the last position of where it returns a list
was found startswith() Returns true if the string starts with
rjust() Returns a right justified version of the the specified value
string strip() Returns a trimmed version of the
28