In the last session, we learned how to do operations using integer and float variables.
We can do some operations with string variables too! Let’s take a look.
- Define two strings w1 and w2 , once with the string ‘Carol’ and the other with ‘Tuesday’.
Now write and run the following:
print(w1+” and “+w2)
Note the added space before and after ‘and’ to print out a syntactically proper phrase.
2. Run the following and see what happens!
a_word = ‘hello!’
an_Echo = a_word*10
print(an_Echo)
3. Do the same with below:
tolerable= ‘Are we there yet? ‘
annoying = tolerable*30
print(annoying)
4. Try running the following and see what happens.
a=1
b=2
c = ‘buckle my shoe’
print(a+b+c)
5. Clearly, we cannot add integers to strings. But we can do other good stuff with string and numbers – its ok.
Let’s start with the following. Write and run.
powerSource = ‘Grayskull’
print(‘He-man has the power of %s’ %powerSource)
6. Write and run:
name = ‘Kenpachi’
number = 13
print( “%s is the captain of Squad %d” %(name, number))
7. These are called ‘string formatting’ . The % operation is NOT A MODULO, but used to format a set of variables that are grouped together in a ‘tuple’ [e.g. (name, number)] . %d, %s are called argument specifiers.
We can use %f as an argument specifier for floating point (decimal) numbers. Also we can use
%.<number of digits>f to set the specific number of digits after the decimal point of a floating number.
Write and run the following
piValue = 3.14159
print(“The constant ‘pi’ is also known as the Archimedes’ constant and has the value %f” %piValue)
print(“The constant ‘pi’ is also known as the Archimedes’ constant and has the value %.4f” %piValue)
print(“The constant ‘pi’ is also known as the Archimedes’ constant and has the value %.2f” %piValue)
Exercise:
Print the sentence (no underline – just print the sentence normally) :
Mushfiqur Rahim is a 33-year-old Bangladeshi cricketer with a batting average of 36.31 in ODI.
But extract the four underlined parts from stored variables. You can choose your own variable names.