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
myString = raw_input("Enter a string! ")
strLength = len(myString)
print "The string \"%s\" has length %d!" % (myString, strLength)
Enter a string! hello world
The string "hello world" has length 11!
>>> print len('abc')
2. String concatenation: the + operation
"Glue" two strings together to form a new string.
myString = "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
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.
print "-" * 80
Note: * is overloaded.
4. Testing for membership in a string
>>> myString = "help me"
>>>if "el" in myString:
... print "\"el\" is in \"%s\"" % myString
"el" is in "help me"
>>> myString = "hi world hello"
>>> print "hello" in myString
5. Iterating over a string
Strings are sequences of characters, so we can iterate over them.
>>> myString = "hello"
>>> for c in myString:
... print c
6. Evaluating an expression that is stored as a string with eval()
>>> numString = "400"
>>> numString = "3+5"
Indexing - Accessing characters in a string
Recall: The characters in a string are numbered, or indexed, starting at 0. Consider the string "hello world":
- The length of "hello world" is 11.
- The characters have index values of 0 through 10.
- In general, a string of length n has characters with index 0 to n-1
How to access a character in a string - general form:
>>>myString = "help"
>>> # negative offsets - count backwards from end
>>> myString[-1] # first character from end
>>> myString[-2] # second character from end
Example: Print the characters in a string, one per line
someStr = "help"
for i in range(len(someStr)):
Example: Print the characters in a string, in reverse
myString = "help"
# print reverse of string
for i in range(len(myString)-1, -1, -1):
p l e h
Note: Strings are immutable - you cannot change a string. For example, this won't work:
>>> myString = "help"
>>> myString = "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
start and/or end can be omitted, if we only want to specify an end or start position.
- If start is omitted, start at position 0
- If end is omitted, end at index len(stringName) - that is, go out to the end of the string
Remember: The upper bound end is NOT inclusive.
myString = 'kelp'
print myString[0:2] # ke
print myString[:3] # kel
print myString[:-1] #kel
print myString[1:] # elp
string2 = myString[:] # copy myString
myString = "help"
myString = "k" + myString[1:]
What is the output?
Other String Operations -
The String Library
To use the string library, we must import it:
||returns copy of s with first character capitalized
||returns copy of s with first character of each word capitalized
||returns copy of s centered in field of specified width
||returns number of occurrences of str in s
||returns index of 1st occurrence of str in s
||returns copy of s in all lowercase letters
||returns copy of s in all uppercase letters
||split s into a list of substrings (splits at blank spaces)