Strings


Overview

Strings are one of most common data types utilised, these are finite sequences of characters. Strings are notated in python between quotation marks or inverted commas. There is an option to use 3 quotation marks or inverted commas in a row for strings that may contain these characters.
To create a variable and assign it an string value:
customer_name = "Max Python"

customer_address_1 = '1 house road'

customer_address_2 = """S'ton Town"""

customer_address_3 = '''AB1 2CD'''

Indexing Strings

To cut up a string you can use indexing to define a start point and an end point. this is achieved though using square brackets after a variable that contains a string. Note that the first character is at index 0.
string_Exmaple1 = "abcdefghijklmnopqrstuvwxyz"

print (string_Exmaple1[0:4])

print (string_Exmaple1[4:8])
Returns:
abcd
efgh

Building and Adding Strings

We can add strings to other strings with '+'.
string1 = "Hello"
string2 = "World"
string3 = "!!!"

print (string1 + string2 + string3)
print (string1 + " " + string2 + " " + string3)

string1 = (string1 + " " + string2 + " " + string3)

print (string1)
Returns:
HelloWorld!!!
Hello World !!! 
Hello World !!! 
Note that If you want a create a string from other data types, then the other data types will need to be converted into a string with the str() function, otherwise a type error will be raised, for example "TypeError: must be str, not int.".
age = 56
score = 3.4

print ("Age : " + str(age))
print ("Score : " + str(score))
Returns:
Age : 56
Score : 3.4

Common String Methods

Strings come with a bunch of built in methods that allow for strings to be quickly and easily manipulated. Here is an explanation of some common ones.
    len() - This returns the length of the string. This is useful for many applications such as indexing.
    replace(var1, var2) -This searches a string for any instance var1 is in the string. It then replaces this with var2.
    strip() - This removes whitespace at the beginning and end of a string.
    lower() - This method converts a string into all lower case letters.
    upper() - This method converts a string into all upper case letters.
Below is an example of each in action.
title = "Python Coding"
section = "Strings Introduction"
pagenumber = "   45  "
print (len(title))
print (title.replace("Python", "Java"))
print (pagenumber.strip())
print (section.lower())
print (section.upper())
Returns:
13
Java Coding
45
strings introduction
STRINGS INTRODUCTION

Escape Sequences

These special sequences of characters are replaced by the intended meaning of the escape sequence.
Here is a table of some of the more useful escape sequences and a description of the output from them.
Escape Sequence       Meaning
\t                    Tab
\\                    Inserts a back slash (\)
\'                    Inserts a single quote (')
\"                    Inserts a double quote (")
\n                    Inserts a ASCII Linefeed (a new line)
Basic Example
If we wanted to print some data points separated by a tab space we could print this string.
DataString = "0\t12\t24"
print (DataString)
Returns:
0 12 24
Raw Strings
Note that raw strings (a string which include a prefix "r"), string literals will be ignored. This allows these special sequences of characters to be included in strings without being changed
DataString = r"0\t12\t24"
print (DataString)
Returns:
0\t12\t24
Which maybe an undesired output
String Lengths
It should also be noted that string literals are only one character in length.
DataString = "0\t12\t24"
print (len(DataString)))
Returns:
7
The raw string has a length of 9.

Unicode Strings

Python defaults to 8-bit ASCII, while Unicode strings are 16-bit, these allow for a wider rang of characters, including special language characters. Unicode strings feature a u before the string.
message = u"helloPlanet"



Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.


Related Pages

Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.
Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter - Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines