Introduction to Strings in Python
In this lesson you will learn how to work with text data in Python. You will create your first Python strings and attach one string with another.
In the previous exercises we have only worked with numbers.
We have learnt how to assign numbers to variables, like so:
num = 5
However, what if we do not want to store a number but some text in a variable? Let's try it:
text = hello
As you can see, this doesn't work. Python thinks that hello
is a variable.
If we want to store text, we must enclose it in single or double quotes:
text = 'hello'
print(text)
text = "hi"
print(text)
It doesn't matter if you use single or double quotes.
You can even store multiple lines of text if you enclose it with three single or double quotes on each end:
text = '''hello
world'''
print(text)
text = """hi
John"""
print(text)
That's it! We have created our first Python strings!
Sometimes we want to attach one string with another. This is called string concatenation.
The simplest way to concatenate strings is by using the + operator:
text = 'a' + 'b' + 'c'
print(text)
This also works with variables that hold string values:
a = 'Code'
b = 'for'
c = 'fun'
text = a + b + c
print(text)
As you can see, our final string is missing some spaces. Let's add them:
a = 'Code'
b = 'for'
c = 'fun'
text = a + ' ' + b + ' ' + c
print(text)
However, adding spaces like this is a bit cumbersome. There's a more efficient way to do this using the join method: 'separator'.join([a,b,c...])
With the join method, we can specify a separator that separates the strings that we put inside the square brackets. In our case it is an empty space:
a = 'Code'
b = 'for'
c = 'fun'
text = ' '.join([a,b,c])
print(text)
We can also specify a different separator:
a = 'Code'
b = 'for'
c = 'fun'
text = '+'.join([a,b,c])
print(text)
What will be the output?
a = 'Hello'
b = 'World'
print(a + b)
What will be the output?
a = 'Hello'
b = 'World'
print(''.join([a,b]))
What will be the output?
a = 'Hello'
b = 'World'
print(' '.join([a,b]))
What will be the output?
a = '1'
b = '2'
print(a + b)