SmithLogo

CSC 111

Introduction to Computer Science Through Programming

Smith Computer Science



Lecture Notes 05: String and formatting basics





Recap: Printing

Default printing


The default print "adds" a "new line" after every print statement:

print('this is one line')
print('this is another')


Try it here

Continuious printing


If, for any reason, you want print to NOT add a newline after the text, you can do this:

print('this is one line;', end = " ")
print('this is in the same one;')
print('this is a new one')


(Note that the third print displays in a second line because the second print is the default one that adds a newline)

Try it here

Space vs NO-space
Notice that if we run the following example: with space, we end up with the output:
abcd def

But if we run this example: with nothing, we end up with the output:
abcddef

The only difference is the end character that was specified; in one it is a space (" "), and in the other a "nothing" ("").

Multi-element printing


You can print multiple elements by separating them with commas:

x = 2
print("My name is", "Pablo;", "My dog, Yak, is", x, "years old.")


Try it here




Intro to Strings

Strings are sequences of characters with some nice properties and "powers".

We can store strings inside variables or we can use them directly (for example when printing).

One type of string (which we've used before) is a String Literals.
String literals are strings that are explicitly specified in a source program by surrounding them with single, double, and even triple quotes.
(That's why triiple quotes are not comments... they are unused string literals!)

For example, in the program shown below:

print('hello world!')
The string literal is: hello world! since it is the text surrounded by single quotes.

A basic property of Strings is that they:

For example, in the program shown below:
print('5 + 7')

There is no expression to be executed inside the print statement since it is a string literal: 5 + 7.

String variables

We can assign string literals to variables that "hold" the text for later use.

An example is shown below:
word = 'bird'
print (word)
link here, in case you haven't heard (not in class)

Strings and indices

A string, as we said, is composed of a sequence of characters.

Each character has a specific position in the string. We call this position its index and we start indexing at 0.

For example, the string literal hello world! is composed of the following characters at the following indices:
0 1 2 3 4 5 6 7 8 9 10 11
h e l l o w o r l d !


Why do we start at 0?
Think of an index as the number of "places" away from the start of the string.
Another point of view is that of a competition, where we have a "champion" (at the top) and then "1st runner up", "2nd runner up", and so forth.

Accessing a specific character in a String

Say we have the string hello world! saved in a variable called greeting.

We can "access" or "retreive" (without removing) a character from a String by indicating which index in particular inside the string you are interested in getting.

You do this by using the square bracket notation:

greeting[6]

This would obtain the character in the index equal to 6: character w.

Activity 1 [2 minutes]:
Try out this code snippet

Activity 2 [1 minute]:
What is the largest index we are allowed to use?
Try accessing a larger one in the code linked above.




Built-in functions for Strings

There are some functions to which we "feed" a string as input and some that are "internal abilities of a string".

function with a string parameter

These are functions that accept a string parameter.
You already know one of these:    print( <your string here> )

To show how it works, we'll use the len( <your string here> ) built in function (from length):

Activity 3 [2 minutes]:
Try out this code snippet

Internal string functions

Each string is like a little machine. Think of it as a car. We call these Objects.
To make use of the internal functions of an object is to use the dot notation:
   <your string here> . <name of function> ( <parameters> )

Example:
   greeting.lower( )

The dot notation means: "Look inside and access".
So, in the example:    greeting.lower( )  , the compiler understands that we want to:
  • look inside the variable greeting, and use its function called lower, and give it no parameters.

  • (the function lower() converts the string litteral to lowercase)

    Special characters inside strings

    Sometimes you want to put special characters inside a string that would mess up our string.

    What if you want to include single quotes in your string literal?

    Let's say you want to print the sentence: That's great!.
    You'll notice it has a single quote in the text.

    You can use double quotes to surround text that contains single quotes.

    So you could write the following:
    print("print('hello world!')")
    


    and the part inside double quotes print('hello world!') will NOT be executed as a statement, it will be interpreted literally.

    What if you want to include double quotes in your string literal?

    We could use triple quotes (but this is getting ridiculous).

    Triple quotes have another property: They allow you to write multiline string literals (that's why people use them as comments).

    Is there another way?

    The answer is YES!

    We can use escape characters.

    Escape Characters

    Escape charaters tell the python interpreter (actually, the compiler for the statement), to interpret the next symbol in a different way than usual.

    The character that tells the compiler to start the escape sequence is the backslash   \  

    Some escape sequences are:




    The format function

    format is one of the string internal functions. We can access it using the dot notation.
    format allows us to do fancy formatting on string litterals.

    Before we use it, let's talk about placeholders:

    Activity 4 [2 minutes]:

    Solve the following "riddle":

    If I write the sentence:
    " The      ate the      " ,

    and I mention that the two nouns to be used are dog, and pizza,

    What should the completed sentence be?

    If you think that was not very hard, then you'll master the format function.



    Using the format function

    format uses placeholders to know where to insert certain items.

    A basic example is the following:
    print('the {} ate the {}.'.format('dog' , 'pizza' ))
    


    Activity 5 [2 minutes]:
    try it out in the python visualizer

  • Here, the placeholders are the pairs of curly brackets: {}, and the items are the parameters passed to the format function (inside the parens).
  • Note that there are the same number of placeholders as items


  • So why do something so complicated just to write a sentence?

    because we can:

    Using variables inside format

    In some applications, you want to print a formatted string that depends on the value contained in a variable.

    An example:
    word1 = 'dog'
    word2 = 'pizza'
    print('the {} ate the {}.'.format(word1 , word2 ))
    


    Activity 6 [2 minutes]:
    try it out in the python visualizer

    Adding formatting hints

    You can add formatting hints inside the placeholder for the item you want to format.

    An example:
    Activity 7 [2 minutes]:
    try it out in the python visualizer




    Concatenating strings

    Strings have another nice property, which is, we can concatenate them using th + operator.

    To concatenate is to place one after the other.

    The following example shows how to concatenate two strings (and more):

    my_string = 'The pizza' + ' is $' #first concatenation
    print (my_string)
    print ()
    print ( my_string, '20',', please' ) #multi-element print
    


    Activity 8 [2 minutes]:
    try it out in the python visualizer

    Note that the comma notation inside print causes a space to be added between printed items.
    This causes the dollar sign to be separated from the number and the comma to be separated by one space from the number (annoying no?)

    Activity 9 [2 minutes]:
    Replace the last print statement for one that uses concatenation so that we get the following output:

    The pizza is $20, please




    Using Repl.it

    Now, please access the replit exercise: String Concatenation
    And repeat the "fix" there.

    Now, let's talk about Homework 01.




    Homework

    [Due for everyone]
    Homework 01 is due Friday BEFORE 17:00 (5PM)


    [Optional]