Any time you want to use text in Python, you are using strings. Python understands you want to use a string if you use the double-quotes symbol.

Once a string is created, you can simply print the string variable directly. You can access characters using block quotes.

Related course: Python Crash Course: Master Python Programming!


Define string

Variables can be of the string data type. They can hold characters or text.
If you create string variable x. You can show it on the screen using the print() function.

x = "Hello"

String indexing

Individual characters can be accessed using blockquotes, counting starts from zero.


The first character starts at zero. This may be a bit counter intuitive, but has historic reasons.

Sub string

By using a colon you can create a substring. If no start or end number is written, Python assumes you mean the first character or last character.

Try the example below:

x = "hello world"
s = x[0:3]
s = x[:3]

Complete example

This example does a lot of string operations like printing text, numbers, combining strings, slicing and accessing elements.

Try the program below:

x = "Nancy"

# Combine numbers and text
s = "My lucky number is %d, what is yours?" % 7

# alternative method of combining numbers and text
s = "My lucky number is " + str(7) + ", what is yours?"

# print character by index

# print piece of string

You should see this output:

python strings


Try the exercises below

  1. Make a program that displays your favourite actor/actress.
  2. Try to print the word ‘lucky’ inside s.
  3. Try to print the day, month, year in the form “Today is 2/2/2016”.

Download answers