Strings in Python
: MachineLearning.org.in¶
Strings are used in Python to record text information, such as name. Strings in Python are actually a sequence, which basically means Python keeps track of every element in the string as a sequence. For example, Python understands the string “hello’ to be a sequence of letters in a specific order. This means we will be able to use indexing to grab particular letters (like the first letter, or the last letter).
This idea of a sequence is an important one in Python and we will touch upon it later on in the future.
In this lecture we’ll learn about the following:
1.) Creating Strings
2.) Printing Strings
3.) Differences in Printing in Python 2 vs 3
4.) String Indexing and Slicing
5.) String Properties
6.) String Methods
7.) Print Formatting
Creating a String¶
To create a string in Python you need to use either single quotes or double quotes. For example:
# Single word
'python'
# Entire phrase
'This is also a string'
# We can also use double quote
"String built with double quotes"
# Be careful with quotes!
' I'm using single quotes, but will create an error'
The reason for the error above is because the single quote in I’m stopped the string. You can use combinations of double and single quotes to get the complete statement.
"Now I'm ready to use the single quotes inside a string!"
We can also use triple quotes. They function the same way as double and single qoutes.
"""This is a string with triple qoutes"""
Just like using double qoutes to use single qoutes without escape characters, we can do the same with double quotes and triple quotes. But its not optimal since you have to put an extra line in between them.
"""The man said "What is that going on over there!" """
"""The man said "What is that going on over there!""""
Must add space
So just use the single quotes around double quotes first.
'There went "The Animal"'
Escape characters.
If there is some where situation where you need a bunch of quotes, you can use escape character \’ \’.
Just make sure you close the end of the string without the escape character .
'There went the man called \'Boaty McBoatFace\''
Printing a String¶
Using Jupyter notebook with just a string in a cell will automatically output strings, but the correct way to display strings in your output is by using a print function.
# We can simply declare a string
'Hello World'
# note that we can't output multiple strings this way
'Hello World 1'
'Hello World 2'
print('Hello World')
print('Hello World')
The combination “\n” makes a newline appear in a string. You can use newlines anywhere you like in a string.
print("\nHello everyone!")
print("\tHello everyone!")
String Basics¶
We can also use a function called len() to check the length of a string!
Sidenote: We can check the length of any data types that are collections with the same len() “call”.
It is considered a built-in function.
len('Machine Learning')
String Indexing¶
We know strings are a sequence, which means Python can use indexes to call parts of the sequence. Let’s learn how this works.
In Python, we use brackets [] after an object to call its index. We should also note that indexing starts at 0 for Python. Let’s create a new object called s and the walk through a few examples of indexing.
# Assign s as a string
s = 'Hello World'
#Check
s
# Print the object
print(s)
Let’s start indexing!¶
s = "MachineLearning.org.in"
print(s) # Prints complete string
print(s[0]) # Prints first character of the string
print(s[7:15]) # Prints characters starting from 3rd to 5th
print(s[7:]) # Prints string starting from 3rd character
print(s * 2) # Prints string two times
print('www.' + s) # Prints concatenated string
print(s[:]) # Prints complete string with range start to end
print(s[::]) # Prints complete string with range start to end with increment 1
print(s[::2]) # Print String with increment of 2
print(s[-1]) # print last character of a string
print(s[-3:]) # print last 3 character of a string
String Properties¶
Its important to note that strings have an important property known as immutability. This means that once a string is created, the elements within it can not be changed or replaced. Immuntiblity is a concept seen in other data types.
Immutability means that the data cannot mutate, aka the data cannot change. A new ‘data object’ needs to be created instead.
For example:
# Let's try to change the first letter to 'x'
s[0] = 'x'
Notice how the error tells us directly what we can’t do, change the item assignment!
Something we can do is concatenate strings!
s
Concatenate just means joining two strings together. Its a term used in other programming languages. But, don’t be scared about the terms.
# Concatenate strings!
s + ' concatenate me!'
# We can reassign s completely though!
s = s + ' concatenate me!'
s
print(s)
We can use the multiplication symbol to create repetition!
letter = 'z'
letter*10
Basic Built-in String methods¶
Objects in Python usually have built-in methods. These methods are functions inside the object (we will learn about these in much more depth later) that can perform actions or commands on the object itself. To keep it brief, methods are actions that a ‘data thing’, aka an object like a string, can take. Functions are actions that belong to no ‘data thing’ aka object, and just exist in the program.
We call methods with a period and then the method name. Basically, we say ‘Hey object, do this to these things”. The things in question that we are asking the object to mess with are placed in the parameters.
Methods take the form:
object.method(parameters)
Where parameters are extra arguments we can pass into the method. Don’t worry if the details don’t make 100% sense right now. Later on we will be creating our own objects and functions! But, to keep it brief, parameters represent what the action for the object should take. The arguments are the actual ‘data things’ that it needs to take.
Here are some examples of built-in methods in strings:
s="Machine Learning"
print(s.upper())
print(s.lower())
print(s.swapcase())
print(len(s))
print(s.isupper())
print(s.islower())
print(s.isnumeric())
print(s.isdigit())
print(max(s))
print(min(s))
s='this is a string...wow'
s.capitalize()
str='hello world, welcome to python tutorials'
print (str.center(60,"-"))
s='this is a string..wow and wow!!!'
print (s.count('i',2,40)) #s.count(string,start,end)
print (s.count('wow'))
Print Formatting¶
We can use the .format() method to add formatted objects to printed string statements.
The easiest way to show this is through an example:
Name='Python'
Age=32
print("My name is",Name,"and Age is",Age)
print("My Name is %s and Age is %d"%(Name,Age))
print("My Name is {} and Age is {}".format(Name,Age))
print("My Name is {0} and Age is {1}".format(Name,Age))
print("My Name is {1} and Age is {0}".format(Name,Age))
print(f"My Name is {Name} and age is {Age}")
print(f"My Name is {Name} and age is {Age} and Sum is {10+20}")
Split Function¶
s="Welcome to Python"
s.split()
s="Welcome-to-Python"
s.split('-')
Strip Function¶
s=' Python '
print(s)
print(s.strip())
print(s.lstrip())
print(s.rstrip())
s = '$Itronix#'
s = s.lstrip('$')
s = s.rstrip('#')
s
s = '$Itronix#'
s.lstrip('$').rstrip('#')