Introduction to Computer Programming-Python Strings

Strings are a fundamental data type that allow programs to store text.

Given the following python code, predict the output:

Code

Output-Completed by Student

myName = "Joe"

print type(myName)

<type 'str'>

Each character of a string is indexed, where the first character is designated a position 0.

H

e

l

l

o

B

o

b

Index

0

1

2

3

4

5

6

7

8

Example of string indexing:  print myName[2]                 Output: _l__

String Constants

Code

Output

print ""

         

print 'Hello, world.'

Hello, world

print "Goodbye, cruel world."

Goodbye, cruel world.

print "It's a beautiful day."

It's a beautiful day.

print """This is
a multi-line
string."""

This is

a multi-line

string.

Why would we have the option of “ or ‘ to create a string?

One might desire to use “ or ‘ in their string

Operations on Strings

We can concatenate (combine) strings.  Here are some common METHODS** on strings.  The method is indicated by the following format:

string.method(Arguments) 

-this is a big deal-

Name*

Code

Output

Concatenation

print 'hello' + ' ' + 'world!'

Hello world!

Copy

print 'hello' * 2

hellohello

Slice

print 'abcde'[1:3]

bc

Find (letter)

print 'abcbac'.index('c')

2

Find (string)

print 'abcbac'.index('ba')

3

Count

print 'abcbac'.count('c')

2

*You can access the API for details on all available string methods.

**Note: Some Python books/courses will call methods, functions, more on this later...