9. Strings - Other Functions#

9.1. Duplication#

We can make multiple copies of a string with * followed by an integer.

1print("test" * 5)
2a = 2
3s = "test"
4print(s * a)
testtesttesttesttest
testtest

9.2. Changing Case#

Python also has several string methods to change the case of a string.

1line = "a tale of two cities"

Capitalize the first word:

1line.capitalize()
'A tale of two cities'

Capitalize all of the words:

1line.title()
'A Tale Of Two Cities'

Convert all characters to uppercase:

1line.upper()
'A TALE OF TWO CITIES'

Convert all characters to lower case:

1'A Tale Of Two Cities'.lower()
'a tale of two cities'

9.3. Aligning Strings#

Python also offers a way to align a string within a given number of characters (by default, a space). You can specify a fill character in the optional second argument.

1line = 'A tale of two cities'
2line.center(50)   # center the string within 50 spaces
'               A tale of two cities               '
1line.center(50,'-')
'---------------A tale of two cities---------------'
1line.ljust(50)    # left justify the string within 50 spaces
'A tale of two cities                              '
1line.rjust(50)    # right justify the string within 50 spaces
'                              A tale of two cities'

9.4. Exercises#

  1. Capitalize each word in the following string:
    book_title = 'the hitchhiker\'s guide to the galaxy'