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/ 18
COMP-122
INTRODUCTION TO COMPUTER PROGRAMMING Lecture 4: Strings
CSIT Department | MIT
Outline +Definition +Creating String +Formatting String Output +String Indexing and Slicing +String Functions +String Input and Output Definition +A string is a sequence of characters. +String is a data type in Python for dealing with text +Typing string values in Python code is fairly straightforward: they begin and end with the quotes. Creating a String +A string is created by enclosing text in quotes. You can use either single quotes, ', or double quotes, ". +A triple-quote can also be used for multi-line strings: Creating a String cont… + An escape character lets you use characters that are otherwise impossible to put into a string >>> print(““I love programming”, Tony said”) Syntax error + An escape character consists of a backslash (\) followed by the character you want to add to the string:
+ Other escape characters include: \' Single quote
o \’ for single quote o \” for double quote o \t for Tab o \n for Newline (line break) o \\ for Backslash Formatting String Output +Format string is a way of making strings that have variables embedded in them +You embed variables inside a string by using a special {} sequence and then put the variable you want inside the {} characters. These are braces { }. They are sometimes called "curly brackets +You must start the string with the letter f for “format,” as in f"Hello {name}". This little f before the " and the {} characters tell Python 3, “Hey, this string needs to be formatted. Put these variables in there.” Formatting String Output cont... (2) +Strings in Python have also a unique built-in operation that can be accessed with the % operator. +This lets you do simple string positional formatting very easily.
+Here we have used the %s format specifier to tell Python where
to substitute the value of name, represented as a string. Formatting String Output cont... (3) oApart from using the print f and % operator for formatting string, python format() function has also been introduced for handling complex string formatting more efficiently.
oThis method of the built-in string class provides functionality
for complex variable substitution and value formatting oThe general syntax of format() method: string.format(var1, var2, ….) Formatting String Output cont... (4) +Formatters work by putting in one replacement field and placeholder defined by a pair of curly braces {} into a string and calling the str.format() function. +The value we wish to put into the placeholders and concatenate with the string are passed as parameters into the format function. >>> user = “Root1000” >>> print(“Hello {}!”.format(user))
>>> fname = “John”
>>> sname = “Doe” >>> print(“His name is {} {}”.format(fname, sname)) String Indexing +Each character in a string has a numbered position called an index +In Python counting always starts at zero. To get the character at the beginning of a string, you need to access the character at position 0. +You can access the character at the Nth position by putting the number N in between two square brackets [] immediately after the string: String Slicing +A slicing is used to pick out part (substring) of a string +The basic structure is: string name[starting location : ending location+1] +You can leave either the starting or ending locations blank. String Slicing cont… +There is an optional third argument, that can specify the step.
+Steps through the string by twos, selecting the characters
at indices 0, 2, and 4. String Functions +Strings come with a ton of methods that return information about the string or return a new string that is a modified version of the original. +Strings provide methods that perform a variety of useful operations. String Functions conti… (2) Here are some of the most useful string functions: +lower(): returns a string with every letter of the original in lowercase >>> “MUST”.lower() MUST +upper(): returns a string with every letter of the original in uppercase +replace(x, y): returns a string with every occurrence of x replaced by y String Methods conti… (3) +count(x): counts the number of occurrences of x in the string +index(x): returns the location of the first occurrence of x +isalpha(): returns True if every character of the string is a letter +isdigit() - Returns True if all characters in the string are digits +startswith(x), endswith(x): returns True if the string value they are called on begins or ends with x respectively. +find(x): find the location of x string in another string +split(): break a string into a list String Functions conti… (5) +join(): It takes a list of strings and concatenates the elements. +join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:
+len(): used to determine a string’s length
String Input and Output Python has an input function which lets you ask a user for some text input and then print the entered input on the screen using print function. 1. input(prompt): To accept input from a user. 2. print(): To display output on the console/screen. End.