[Python Beginner][Part2 b] Strings.

Abhinav Mahapatra
2 min readJan 26, 2019

--

Welcome.

The basic idea is to introduce you to the building blocks of all python code you will write in the future.

What is a string?

Fundamentally, strings are a set of characters.

We can declare a string in two ways :

  1. Single quote strings
  2. Double quote strings
single_quote_string = 'Hello there'
double_quote_string = "Hi there"

print(single_quote_string)
print(double_quote_string)

how to check what data type the variable is? use type() function

var = "hi there"
print(type(var))

of course, we can mix and match the single and double quotations in a string.

var = "so robert said, 'I will not make it!' before going to his room."
print(var)
print(type(var))

Now, there are some nifty inbuilt functions we can use with strings.

a. String function: Changing the case

var = "erica"
print(var.title())

title() function makes sure the first alphabet is capitalized of each word.

var = "erica. you there?"
print(var.upper())
print(var.lower())

upper() and lower() change the case to uppercase and lower case respectively.

We will be seeing this style of function call a lot initially.

variable.action()

This basically means to apply the method to the variable. We will delve in this later.

b. String function: Combining strings(concatenation)

var_1 = "Sunday "
var_2 = "holiday"

full_sentence = var_1 + var_2

print(full_sentence)

Simply using ‘+’ sign will concatenate the strings together.

We can also do this:

var_1 = "Sunday "
var_2 = "holiday"

full_sentence = var_1+'is a '+var_2

print(full_sentence)

c. String function: Adding whitespace/newline

# \t = whitespace
# \n = newline

var = "Sunday\tholiday"
print(var)

var = "Sunday\nholiday"
print(var)

Pretty simple, \t will add a space and \n will add a newline whenever it is passed through the print() function.

d. String function: Stripping whitespace

var = ' Sunday '
# strips the whitespace on left
print(var.lstrip())
# strips the whitespace on right
print(var.rstrip())
# strips the whitespace on both sides
print(var.strip())

lstrip(): Strips the whitespaces on the left of the sentence
rstrip(): Strips the whitespaces on the right of the sentence
strip(): This is a combination of the above two.

We sometimes need to clear the whitespaces in order to add further strings at the end of the current ones(concatenation) and having whitespaces will make this process a bit more complicated.

Think of this as cleaning a string wherever needed.

Exercises to do

Q. “Ken Thompson once said, ‘One of my most productive days was throwing away 1000 lines of code’”. Print the quote as it is.

Q. Store your name is a variable. Print the variable in lowercase, Titlecase and UPPERCASE respectively.

Q. Store your first name in var1 and surname in var2. Print your full name with space in between.

--

--