Strings in Python

my_name = 'Zed A. Shaw'

my_age = 35 # not a lie

my_height = 74 # inches

my_weight = 180 # lbs

my_eyes = 'Blue'

my_teeth = 'White'

my_hair = 'Brown'

print "Let's talk about %s." % my_name

print "He's %d inches tall." % my_height

print "He's %d pounds heavy." % my_weight

print "Actually that's not too heavy."

print "He's got %s eyes and %s hair." % (my_eyes, my_hair)

print "His teeth are usually %s depending on the coffee." % my_teeth

# this line is tricky, try to get it exactly right

print "If I add %d, %d, and %d I get %d." % (

my_age, my_height, my_weight, my_age + my_height + my_weight)

String Methods

.upper() & .lower()

The .upper() and .lower() string methods are self-explanatory. Performing the .upper() method on a string converts all of the characters to uppercase, whereas the lower() method converts all of the characters to lowercase.

1
2
3
4
5
6
7 / > s = “Whereof one cannot speak, thereof one must be silent.”
> s
'Whereof one cannot speak, thereof one must be silent.'
> s.upper()
'WHEREOF ONE CANNOT SPEAK, THEREOF ONE MUST BE SILENT.'
> s.lower()
'whereof one cannot speak, thereof one must be silent.'

.count()

The .count() method adds up the number of times a character or sequence of characters appears in a string. For example:

1
2
3 / > s = "That that is is that that is not is not is that it it is"
> s.count("t")
13

.find()

We search for a specific character or characters in a string with the .find() method.

1
2
3 / s = "On the other hand, you have different fingers."
> s. find("hand")
13
1
2 / > s.find("o")
7

But if we want to find the second “o” we need to specify a range.

1
2 / > s.find("o", 8)
20

.replace()

Let’s say we want to increase the value of a statement. We do so with the .replace() method. For example:

1
2
3
4
5 / > s = "I intend to live forever, or die trying."
> s.replace("to", "three")
'I intend three live forever, or die trying.'
> s.replace("fore", "five")
'I intend to live fivever, or die trying.'