The String Data Type


Review Exercise: Write a program that computes the sum of a list of integers that are provided by the user. The user hits the enter key to indicate that they have entered all the numbers.

Hint: Remember how to convert a string to a numeric type?
number = float("34")   # now number contains the float 34.0





Some Basic String Operations


1. Computing the length of a string: the len() function

Example:
myString = raw_input("Enter a string! ")
strLength = len(myString)
print "The string \"%s\" has length %d!" % (myString, strLength)

Sample Run:
Enter a string! hello world
The string "hello world" has length 11!


Example:
>>> print len('abc')
3


2. String concatenation: the + operation

"Glue" two strings together to form a new string.

Example:
myString = "call " + "911"
print myString

Output:
call 911


Note: + is overloaded in Python, i.e., it means different operations depending on the type of its operands.

    * 3 + 5   # + means addition
    * "hello " + "world"  # + means concatenate


Note: Strings cannot be concatenated with values that are not strings. For example, this produces an error:

>>> x = "call " + 911
TypeError: cannot concatenate 'str' and 'int' objects


We can fix this problem by first converting the number to a string:

>>> x = "call " + str(911)
>>> print x
call 911


Example: Concatenation assignment operator
>>> myString = "help"
>>> myString += " I got a spam burger for dinner"
>>> print myString
help I got a spam burger for dinner


3. String repetition: * operator

We can repeat a string, or concatenate a string with itself, any number of times with the * operator.

Example:
>>>print "hello"*3
hellohellohello

Example:
print "-" * 80  
---------------------------------------------------------------------------------


Note: * is overloaded.




4. Testing for membership in a string

Example:
>>> myString = "help me"
>>>if "el" in myString:
...        print "\"el\" is in \"%s\"" % myString

"el" is in "help me"



Example:
>>> myString = "hi world hello"
>>> print "hello" in myString
True


5. Iterating over a string

Strings are sequences of characters, so we can iterate over them.

Example:
>>> myString = "hello"
>>> for c in myString:
...           print c




h
e
l
l
o


6. Evaluating an expression that is stored as a string with eval()


Examples:
>>> numString = "400"
>>> eval(numString)
400
>>> numString = "3+5"
>>> eval(numString)
8


 




Indexing - Accessing characters in a string


Recall: The characters in a string are numbered, or indexed, starting at 0. Consider the string "hello world":


h e l l o   w o r l d
0 1 2 3 4 5 6 7 8 9 10




How to access a character in a string - general form:

stringName[index]


Example:
>>>myString = "help"
>>> myString[0]
'h'
>>> myString[1]
'e'
>>> # negative offsets - count backwards from end
>>> myString[-1]   # first character from end
'p'
>>> myString[-2] # second character from end
'l'


Example: Print the characters in a string, one per line
someStr = "help"
for i in range(len(someStr)):
    print someStr[i]

Output:
h
e
l
p



Example: Print the characters in a string, in reverse
myString = "help"

# print reverse of string
for i in range(len(myString)-1, -1, -1):
   print myString[i],

Output:
p l e h



Note: Strings are immutable - you cannot change a string. For example, this won't work:

>>> myString = "help"
>>> myString[0] = "k"
This produces an error!




Slicing - a new object that contains a section of a string


General Form: To get the substring consisting of characters in positions start through end-1 in a string

stringName[start:end]



start and/or end can be omitted, if we only want to specify an end or start position.


Remember: The upper bound end is NOT inclusive.
Examples:
myString = 'kelp'
print myString[0:2]  # ke
print myString[:3]    # kel
print myString[:-1]   #kel
print myString[1:]    # elp
string2 = myString[:]  # copy myString


Example:
myString = "help"
myString = "k" + myString[1:]
print myString

What is the output?





Other String Operations -
The String Library


Note:
To use the string library, we must import it:
import string


Function Purpose
capitalize(s) returns copy of s with first character capitalized
capwords(s) returns copy of s with first character of each word capitalized
center(s, width) returns copy of s centered in field of specified width
count(s, str) returns number of occurrences of str in s
find(s, str) returns index of 1st occurrence of str in s
lower(s) returns copy of s in all lowercase letters
upper(s) returns copy of s in all uppercase letters
split(s) split s into a list of substrings (splits at blank spaces)