You are on page 1of 5

APPLICATION LABORATORY II

Sherina Sally

Strings in Python Department of ICT


Faculty of Technology,
University of Colombo

PYTHON STRINGS …(1)


• A sequence of characters

• Used to store textual values

• Immutable
All Rights Reserved

• Each character of the string can be accessed using the position of the element
- Positioning starts from 0
- Python supports negative indexing
- Python doesn’t have a separate data type to represent characters

Department of ICT, Faculty of Technology, University of Colombo All Rights Reserved 2

1
PYTHON STRINGS …(2)
• Obtain the length of a String by len()

• Check whether a substring is present in a string use in

- “ring” in “string”  returns True

All Rights Reserved


• Check whether a substring is not present in a string use not in

- “rings” not in “string”  returns True

• Delete the entire string using the del keyword

Department of ICT, Faculty of Technology, University of Colombo All Rights Reserved 3

STRING SLICING
• Extracts a part from a string as a substring

str[a : b]
All Rights Reserved

• starting index • end index


• zero based index • excluding the bth character

Department of ICT, Faculty of Technology, University of Colombo All Rights Reserved 4

2
STRING OPERATORS
• Combines two strings by the “+” operator

str1 + str2

All Rights Reserved


• To combine the same string several times repetitively, use “*”

str1 * 3

Department of ICT, Faculty of Technology, University of Colombo All Rights Reserved 5

format() …(1)
• Combines numerals to strings through placeholders

str = “My Birthdate is on { 0 }/{ 1 }/{ 2 }”


All Rights Reserved

print( str.format (birthDate, birthMonth, birthyear) )

Department of ICT, Faculty of Technology, University of Colombo All Rights Reserved 6

3
format() …(2)

str = “My Birthdate is on { date }/{ month}/{ year }”

All Rights Reserved


print( str.format (date = 1, month = 1, year = 2000) )

Department of ICT, Faculty of Technology, University of Colombo All Rights Reserved 7

STRING FUNCTIONS

lower() Converts the string to lowercase str.lower()


islower() Checks if the string is in lowercase str.islower()
upper() Converts the string to uppercase str.upper()
All Rights Reserved

strip() Removes the leading and trailing str.strip()


whitespaces in a string
replace() Replaces a string with another string str.replace(str1, str2)
split() Splits a string by a given separator str.split(separator)
find() Returns the first occurrence of a string str.find(string)
to be found within another string
isdigit() Checks if all characters are numeric str.isdigit()

Department of ICT, Faculty of Technology, University of Colombo All Rights Reserved 8

4
Department of ICT, Faculty of Technology, University of Colombo

You might also like