Python Programming for Beginners (2015)
Chapter Four: Playing With Words
In this chapter, you will learn:
· How to work with string variables in Python
· How to format strings variables in Python
In this chapter we will go through some operators for string variables. You will need to use words throughout your program in order to tell the user what to do and to display all of the things your program is doing in the background.
Linking Strings Together
Sometimes you will have two strings which you need to link together during your program. You may use this if you want to take a users name full name and you want to refer to them by their first name, or by “Mr/Miss/Mrs” and their second name, or by their full name.
In this case you will define the users name as follows:
#Defines the users name
user_sex = “Mr”
user_firstname = “David”
user_surname = “Christopher”
You can combine the text by using a + sign in the middle of the words. Something you will find if you use the code print ([user_firstname + user_surname]) will display “DavidChristopher” without any space in between.
You can use this code to put a space in between the words:
print (user_firstname, user_surname)
You can use the % operator to format strings. This works by writing your string and adding the % symbol. Then add brackets which include the variables and values which will be added to the string.
We have already defined some variables in the last section which we will use in this example of how to format strings.
set_message = “Welcome to this program %s %s %s”
(user_sex, user_firstname, user_secondname)
If you save this script and then run it you will find that it prints out as “Welcome to the program Mr David Christopher”. %s, %s and %s are used as place-holders which are replaced with the variables and values you input in the brackets underneath.
When you format using this method you use %s to signify a string, %d to signify a number and %4.2f to signify a float. The 4 in the %4.2f signifies the total number length and the 2 signifies the decimal places.
Setting String Case
You can also easily set the case of the string when you are displaying it on the screen. For example you can use the code print (user_firstname.upper()) which will display the first name in upper case. If you use the code print (user_firstname.lower()) it will display the first name in lower case.
See what I said about Python being simple?