Tuesday 8 September 2020

Part One: Exercise 4

 In this exercise, we are going to study different ways to manipulate strings in Python 3. For example if a user inputs some strings, how do we convert it to all lower case, or all upper case or title case?

We do this by using what is known as methods. This is done by variable dot method. Example username.lower().

The .lower() is the method to convert the string stored in the variable username to all lower case.

There are a lot of methods in Python 3 but we are going to only focus on the few in this exercise.

Write a program to take a message input from the user and do the following:

-change the string to all lower case

-change the string to all upper case

-change the string to title case

-change the string to swap case

Here is my solution below. My input was “Hello World”.

 

          print('*' * 50) #prints * 50 times

print('A PROGRAM TO MANIPULATE THE FORMATTING OF STRINGS')

print('*' * 50)

print()         #prints a blank line

text = input('Please enter some text: ') #user enters some text here

print()      

print(len(text)) #prints the length of the text inputed

print('-' * 40)

print(f'{text} lower case is,',text.lower()) #changes text in lower case

print('-' * 40)

print(f'{text} upper case is,',text.upper()) #changes text in upper case

print('-' * 40)

print(f'{text} title case is,',text.title()) #changes text in title case

print('-' * 40)

print(f'{text} swap case is,',text.swapcase()) #changes text in swap case

print('=' * 50)


There are a lot more methods that can be applied to strings that you may explore.

You can test strings to get a True or False or you could check for specific letters. Try these below:

print(text.startswith('H'))

print(text.startswith('h'))

print(text.endswith('d'))

print(text.istitle())

print(text.isupper())

print(text.islower())

print(text.isalpha())


You can split strings too.

print(text.split())

 


No comments:

Post a Comment