Computer Science

# Strings

We have previously seen strings. Here we will show you quite a few more details.

First, a string is surrounded by single or double quotes:

name = 'Mariano'
food = "homemade lasagna is the best"

You can use several operations with strings. If you add strings, they are concatenated. So this:

result = 'fire' + 'place'

will set result to 'fireplace'.

Adding is particularly useful when you want to accumulate a result. For example:

def collect_vowels(string):
result = ''
for character in string:
if character in 'aeiou':
result += character

return result

print(collect_vowels('crazy time'))

In this code we use the result variable to accumulate all of the vowels in the string, and we use the += to add in each vowel. This code prints:

aie

## Multiplying strings

If you multiply strings, they are duplicated. So this:

result = 'wow' * 3

will set result to 'wowwowwow'.

Here is an illustration of how to use both multiplication and addition of strings. This function wraps text in a banner.

def banner(text):
"""Wrap the text in banner"""
size = len(text)
return '-' * size + '\n' + text + '\n' + '-' * size

result = banner('Go cougars!')
print(result)

Notice how we use '-' * size to get one asterisk for every character in the input text. Likewise we use + to add the banner, newline, and text.

This code prints three lines of text:

-----------
Go cougars!
-----------

## Iterating over the characters in a string

You will recall that we have iterated over numbers:

numbers = [1, 2, 3]
for number in numbers:
print(number)

and the lines in a file:

with open('input.txt') as file:
for line in file:
print(line)

We can likewise iterate over the characters in a string:

line = 'what a life'
for character in line:
print(character)

This will print out each character, including spaces, on a separate line:

w
h
a
t

a

l
i
f
e

## Functions for testing strings

Following are some of the functions you can use to test strings:

• isalpha(): true if all characters are alphabetic
• isdigit(): true if all characters are digits
• isalnum(): true if all characters are alphanumberic (alphabetic or digits)
• isspace(): true if all characters are white space (space, tab, newline)

For example:

'a'.isalpha()     # True
'ab3'.isalpha()   # False
'8'.isdigit()     # True
'89a'.isdigit()   # False
'89a'.isalnum()   # True
' \t\n'.isspace() # True

All of these functions work on variables that reference strings. For example:

password = 'adam123'
print('Yes')
else:
print('No')

This will print Yes.

## Capitalization

These functions will test or change capitalization:

• islower(): returns true if all characters are lowercase
• isupper(): returns true if all characters are uppercase
• upper(): returns a new string that is all uppercase
• lower: returns a new string that is all lowercase

For example:

'abc'.islower()    # True
'abC'.islower()    # False
'ABC'.isupper()    # True
'ABc'.isupper()    # False
'abc'.upper()      # 'ABC'
'ABC'.lower()      # 'abc'

## Testing for inclusion

We can test if a string is contained within another string:

'BYU' in 'I am a student at BYU.'        # True
'BYU' in 'This room is full of monkeys'  # False
'll o' in 'This room is full of monkeys' # True

Notice that the last example demonstrates that this is checking only for equality of characters, not words.

## Example: collect digits in a string

This function will accumulate all the digits in a string:

# isdigit
string = 'hello8world10\n'
keepers = []
for character in string:
if character.isdigit():
keepers.append(character)

print(keepers)

This will print:

810

## Example: replace digits in a string

This function will replace all of the digits in a string with a ?:

def no_numbers(text):
result = ''
for char in text:
if char.isdigit():
result += '?'
else:
result += char
return result

print(no_numbers('There were 7 people in 3 rows.'))

This will print:

There were ? people in ? rows.

## Example: collect lowercase or uppercase letters in a string

This example shows how to use in to collect all of the lowercase or uppercase vowels in some text:

vowels = 'aeiou'
vowels += vowels.upper()
print(vowels)

found = ''
for letter in 'The Aeneid is ancient Greek literature.':
if letter in vowels:
found += letter

print(found)

Notice how we use vowels += vowels.upper() to be sure we have a variable that has all of the lowercase and uppercase vowels. Then we can check if any letter is in this string of vowels using letter in vowels.

This code will print:

eAeeiiaieeeieaue

## Example: capitalize some letters in a string

Here is another example that will capitalize every letter of a string that is part of BYU:

def byu(text):
"""Capitalize every letter of text that is part of 'BYU'"""
result = ''
for c in text:
if c in 'byu':
result += c.upper()
else:
result += c
return result

print(byu('Any student, boy or girl, young or old, can be a yodeler.'))

This will print:

AnY stUdent, BoY or girl, YoUng or old, can Be a Yodeler.