3. Working with strings#

Solutions to exercises#

Exercise 3.1.#

Declare a variable named year, and assign it an integer with the value 1879. Next, use this variable to print the following sentence: “Albert Einstein was born in 1879”.

year = 1879
sentence = 'Albert Einstein was born in ' + str(year)
print(sentence)

Exercise 3.2.#

Create a variable and assign it your full name as a string. Next, print the number of characters in your name, excluding the space(s).

Tip: to remove the spaces, you can replace these with an exmpty string (‘’).

name = 'Albert Einstein'
# .replace(str1, str2) replaces all occurrences of the first string with the second
name_no_space = name.replace(' ', '' )
print( len(name_no_space) )

Exercise 3.3.#

Create two string variables. The first variable must be assigned the value ‘unique’ and the second variable should be assigned the value ‘biodiversity’. Create a third variable with the value ‘university’, by firstly slicing the first two string variables, and by subsequently concatenating the substrings.

# Create two string variables word1 and word2
word1 = 'unique'
word2 = 'diversity'

# Combine the values into word3

word3 = word1[0:3] + word2[2:]

# Check by printing the result
print(word3)

Exercise 3.4.#

Create the following two string variables:

first = 'vladimir'
last = 'nabokov'

Using these two existing variables, create a third variable named full_name with the following value: “Nabokov, Vladimir”. Note that the first character of the first name and the last name must be in upper case.

first = 'vladimir'
last = 'nabokov'

# Create the full name in steps, so that our code lines are more readable
# Note that += can be used for string concatenation too
full_name = last[0].upper() + last[1:]
full_name += ', '
full_name += first[0].upper() + first[1:]

# Check the full name
print( full_name )

Exercise 3.5.#

Create a variable named url and assign it following string: https://www.universiteitleiden.nl.

Try to write code which can extract the top-level domain (i.e. the country code) from this url. Tip: this problem can be solved by creating a string slice with the last two characters only, but top-level domains may consist of more than two characters, like ‘.com’ or ‘.amsterdam’. A more generic approach is to make use of the rindex() method, which returns the LAST occurrence of a character.

# Create the variable
url = 'https://www.universiteitleiden.nl'

# and find its Top-Level Domain (TLD)
tld = url[ url.rindex('.')+1 : ]

# Print the result
print( tld )

Exercise 3.6.#

Create a variable named filename and assign it the value ‘README.txt’. Next, write some code in Python which can extract the filename without the extension.

filename = 'README.txt'
index_dot = filename.index('.')
filename = filename[:index_dot]
print(filename)