Python Data Types

String Data Types

Strings are a contiguous set of characters (alphabets, numbers, or symbols). 

Python identifies this contiguous set of characters as a string if these characters are enclosed in double quotes (“) as in the example below.

“I go to Bright Elementary School. I play soccer in my school.”

A string can also be defined by using single quotes (‘) instead of double quotes (“) as in the example below:

‘I go to Bright Elementary School. I play soccer in my school.’

Note you cannot mix single quotes and double quotes in the same string as in the example below.

“I love playing soccer.’ 

The above is not a string because the opening quote is a double quote (“) and the closing quote is a single quote (‘). The two quote symbols do not match.  Python will not like it and will give you an syntax error message. See the Program Example below.

PROGRAM EXAMPLE: SINGLE AND DOUBLE QUOTES IN THE SAME STRING – SYNTAX ERROR EXAMPLE
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> "I love playing soccer.'
SyntaxError: EOL while scanning string literal
>>>

Strings are used to display a message on the computer screen.

How to Declare String Data Type

We declare strings just as we declared numbers by using the assignment operator equal sign (=). 

Let us use the facts of our solar system to explain how to declare and assign value to a string data type,

The rules for treating different Data Types is exlained by using the Slar system facts like planet's distnace from Sun, planet's size, planet's temperature, etc. String, Tuple, Dictionary concatenation, indexing is explained using solar system facts for various Data Types
Our Solar System

In the following program example, ‘X’ defines a string variable using single quotes (‘   ‘). ‘Y’ defines a string variable using double quotes (“  ‘’).

Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep  5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.

X = 'moon distance from earth' # Using single quotes
Y = "moon distance from earth" # Using double quotes

Python will treat the above two variables, X and Y as string variables.

PROGRAM EXAMPLE: STRING DATA TYPE SYNTAX ERROR
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # String Variables
>>> # Use single quotes (')to define a string variable.
>>> # and assign it a value 'mon distance from earth'.
>>> X = 'moon distance from earth'
>>> Python interpreter will treat X as a string variable.
>>>
>>> # Use double quotes (") to define string variable Y. 
>>> # and assign it a value "moon distance from earth". 
>>> # Python interpreter will treat “Y” means "moon distance from earth".
>>> Y = "moon distance from earth"
>>> 
>>> # You cannot define a string by starting with double quote and end with a single quote or vice versa.
>>> Z = "moon distance from earth'
SyntaxError: EOL while scanning string literal
>>> 

Facts About Earth And Moon

The Table below summarizes a few facts about the planet earth and the moon. The program examples below will use these facts.

The Earth We Live on Facts 
Age4.5 billion Years
Distance from Sun93 million miles (150 million km)
Orbits aroundSun
Orbit period365 days
Radius4,000 miles (6,400 km)
Acceleration due to gravity9.8 meter/ sec^2
Earth Planet Facts

Moon

Our Moon orbits around planet Earth and is Earth’s only natural satellite. It is the fifth-largest satellite in the Solar System. It takes the moon 27 earth-days to complete one orbit around the earth. 

Our Moon Facts 
Age4.5 billion Years
Distance from Earth238,000 miles (385,000 km)
Orbits aroundEarth
Orbit period27 earth-days
Radius1,079.4 miles
Acceleration due to gravity1.62 meter/ sec^2
Moon Facts

Strings with Embedded quotes

On the Printing in Python page, we learned how to print strings.  The earlier examples did not have quotes embedded within the strings. Strings that have quotes as part of the string would confuse the Python interpreter since Python uses quotes to identify a sequence of characters as a string. If there are quotes embedded in a string, Python will flag it as a syntax error.  In the Program Example below, the word Moon’s has an embedded quote. Python interpreter flags it as a syntax error.

PROGRAM EXAMPLE: STRINGS WITH EMBEDDED QUOTES – 1
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # Example of Embedded quote in string literal causes syntax error.
>>> 'Moon's distance is 25000 miles from earth'
SyntaxError: invalid syntax
>>>

The reason why Python flags the above as a syntax error is because Python identifies the string ‘Moon’s distance is 25000 miles from earth‘ as a string when it sees the first single quote before the letter M. As the Python interpreter comes across the second quote after character ‘n’ in the word Moon’s, it will assume the end of the string. Python does not expect to see any more characters after the quote in the word Moon’s and gives a syntax error.

Another example of string with embedded quote:

PROGRAM EXAMPLE: STRINGS WITH EMBEDDED QUOTES – 2
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # Another example of embedded quotes in string Variable causes syntax error.
>>> Moon_distance = "My teacher said, "Moon's distance from earth is 250,000 miles.""
SyntaxError: invalid syntax
>>>

In the above example, Python identifies “My teacher said, “Moon’s distance from earth is 250,000 miles.” as a string on seeing the first double quote before the word My. On seeing the second double quote before the word Moon’s, the Python interpreter will assume the end of the string at the second double before the word Moon’s. All characters after the second double quote cause a syntax error.

How Do We Handle Strings That Have Quotes As Part Of String’s Text?

The solution to the above problem is to use what is called an escape character in strings that have embedded quotes.  The escape character is the symbol backslash (\).  If you put a backslash before the quote embedded in the string, Python ignores the embedded slash and treats the embedded quote as a valid character. This is explained in the Program below using five different program examples.

Program 1 shows the syntax error due to the embedded quote in “isn’t”.

Program 2 uses backslash (\) escape character before the quote in isn’t and replaces it with (isn\’t). The backslash eliminates the syntax error.

Program 3 uses backslash (\) escape character before the embedded quote in the word “The. This escape character will ignore the embedded quote (“) in the word “The.

Programs 3a and program 4 uses triple single quotes (‘’’) to bypass the embedded quote issue.

PROGRAM EXAMPLE: ESCAPE CHARACTER USE IN STRINGS WITH EMBEDDED QUOTES
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
# Program 1
>>> water_boiling_point = 'My teacher said, "The water boiling point is'nt 90 degrees Celsius"'
SyntaxError: invalid syntax
>>> 
>>>
# Program 2
>>> water_boiling_point = 'My teacher said, "The water boiling point isn\'t 90 degrees Celsius."'
>>> print(water_boiling_point)
My teacher said, "The water boiling point isn't 90 degrees Celsius."
>>> 
>>>
>>>
# Program 3
>>> water_boiling_point = "My teacher said,\"The water boiling point is 100 degrees Celsius.\""
>>> print(water_boiling_point)
My teacher said, "The water boiling point is 100 degrees Celsius."
>>> 
# Program 3a
>>> water_boiling_point = '''My teacher said, "The water boiling point isn't 90 degrees Celsius"'''
>>> print(water_boiling_point)
My teacher said, "The water boiling point isn't 90 degrees Celsius"
>>> 
# Program 4
>>> water_boiling_point = '''My teacher said, "The water boiling point is 100 degrees Celsius."'''
>>> print(water_boiling_point)
My teacher said, "The water boiling point is 100 degrees Celsius."
>>>

Multi-line Strings

From the above program, we saw how triple quotes (‘’’) can be used to print strings that have embedded quotes (‘) or (“).  Triple single quotes can also be used for multi-line strings.

We introduced the multi-line strings on the Printing in Python page. Let us write a program that prints a multi-line string using triple single quotes. The multi-line string used in the program describes the earth-moon facts. Since the earth-moon facts string is very long, we continue the string onto several lines.

The string uses triple single quotes (‘’’) as below.

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> '''Moon's distance from our planet Earth is 250,000 miles. Moon is planet earth's only satellite. It orbits around planet earth in about 27 days. Its radius is about 1,080 miles.'''
"Moon's distance from our planet Earth is 250,000 miles. Moon is planet earth's only satellite. It orbits around planet earth in about 27 days. Its radius is about 1,080 miles."
>>>

Concatenation of String Literals

We defined literals earlier in this chapter.  To recap, literals are text or numbers whose value is directly visible from their name. String literals are text enclosed in quotes.

If you want to concatenate several literals together, you can do this by typing them next to each other. Python will join them as in the following example program.

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # Example program showing how string literals can be joined together just by typing them next to each other.
>>>
>>> 'Moon distance from ' 'earth is 250' '000 miles.'
'Moon distance from earth is 250000 miles.'
>>> 

Concatenation of String Variables

We saw in the previous section how we can concatenate string literals just by typing them next to each other. Now we will concatenate two string variables together, using the plus (+) symbol. Think of plus symbol as a concatenation operation. We will use the interesting facts about the planet Jupiter to write a program to show how we can concatenate several string variables.

Data Types - Planet Jupiter facts are used in the program to explain concatenation of strings
Data Types Planet Jupiter

Planet Jupiter Facts:

The Romans named the planet after the Roman God, Jupiter.  It is mainly composed of hydrogen and helium with a rocky core of heavier elements. It has 79 moons, more than any other planet in the solar system. The four largest moons are called Galilean Moons since they were discovered by Galileo (Italian mathematician, physicist, philosopher, and astronomer) in the year 1610.  Jupiter has a diameter of about 88,695 miles (142,800 kilometers), which is more than 11 times the diameter of Earth. Jupiter has the strongest magnetic field of any planet in the solar system; it is 14 times the magnetic field of the earth.

Data Types Galileo-Galilei discovered Jupiter four large moons. This section uses Jupiter facts to explain concatenation of strings.
Galileo-Galilei Discovered Jupiter’s four Latge Moons

Source: Wikipedia

Jupiter Facts

JUPITER QUICK FACTSDISTANCE FROM SUNUNITS
Distance from Sun484 million miles (778 million km)
Order from Sun5th 
Orbit duration11.84Earth-years
Rotation10Earth-hours
Size1,300 times volume of earth 
Diameter88,695 miles (142,800 km) 
Moons79 
JUPITER QUICK FACTS

In the program example of string variables concatenation, we will define three string variables ‘planet_name’, ‘size’, and ‘order’ as below.

planet_name = ‘Jupiter’

size= ‘ is 142,984 kilometer diameter’

order = ‘ and is fifth from Sun.’

We will use the plus (+) symbol to concatenate the above three string variables together.

PROGRAM EXAMPLE: CONCATENATION (ADDITION) OF STRING VARIABLES
>>> # String Variable concatenation
>>> planet_name = 'Jupiter'
>>> size = ' is 142,984 kilometer in diameter'
>>> order = ' and is fifth planet from Sun.'
>>> planet_name + size + order
'Jupiter is 142,984 kilometer in diameter and is fifth planet from Sun.'
>>> 

Concatenation of String Literal and String Variable

Sometimes you may want to concatenate (add) string literal and string variable. You can again use the plus (+) symbol to concatenate a string literal with a string variable.  This time let us use planet Mars facts for the program example.

Planet Mars Facts:

Mars was named after the Roman God of War because its color resembles the color of blood. Mars is called the ‘Red Planet’.  It is red because it has Iron Oxide (commonly known as rust) on its surface.  The name of the month of March is derived from Mars.  It is believed that Mars once had water flowing just like earth. Mars has about 1/3 the gravity of earth, Things weigh less on Mars than they weigh on Earth.  This means if your weight is 60 pounds, you will weigh only 20 pounds on Mars. A rock dropped on Mars would fall slower than a rock dropped on Earth.  Mars does not have a magnetic field as we have on earth.

Mars Missions

There have been many missions to mars, including orbiters, landers, rovers, and flybys. The missions include the Mars Curiosity mission in 2012, the MAVEN mission, which arrived on September 22, 2014, and the Indian Space Research Organization’s MOM Mangalyaan orbiter, which arrived on September 24, 2014.  Two robots that move (rovers) are exploring Mars’ surface. Their names are Opportunity and Curiosity. The rovers travel around taking pictures and looking closely at the planet’s soil and rocks.

Mars Curiosity Rover

Curiosity is a car-sized Mars rover designed to explore craters on Mars. Curiosity was launched on 26 November 2011 and landed on Mars on 6 August 2012 after traveling 560 million km (350 million mi). The rover investigated Mars’s climate, rocks, and if the landing crater ever had conditions favorable for microbial life including water. The rover is still operational, and as of March 15, 2021.

Mars facts are used to explain Data Types operations such as addtion, multiplication, concatenation, and indexing.
Mars Curiosity Rover

Perseverance Mars Rover

Perseverance is a car-sized Mars rover designed to explore Mars crater Jezero. It was manufactured by the Jet Propulsion Laboratory and launched on 30 July 2020. The rover successfully landed on Mars on 18 February 2021. Perseverance carries instruments, 19 cameras, and two microphones.[9] The rover is also carrying the mini-helicopter Ingenuity an experimental aircraft that will attempt the first powered flight on another planet.

The rover’s goals include investigating the Mars environment to determine its capability of supporting life, investigating evidence of former microbial life, collecting rock and soil samples, and testing oxygen production from Mars’s atmosphere to prepare for future manned missions.

Source: nasa.gov

MARS QUICK FACTSDISTANCE FROM SUNUNITS
Distance from Sun142 million miles (225 million km)
Order from Sun4th 
Orbit duration687Earth-days
Rotation period24 hours 39 minEarth-hours
Size1/10 of Earth 
Moons2Phobos and Deimos 
Diameter4220 miles (6752 km) 
MARS QUICK FACTS

For our program example, we will define four string variables ‘planet_name’, ‘size’, ‘distance’, and ‘year’. We will use the concatenation operator (+) to concatenate three string variables and one string literal ‘6752 kilometers’ together.

planet_name = ‘Mars’

distance = ‘ Its distance from Sun is 225 million kilometers. ’

Year = ‘ Mars year is 687 earth days.’

PROGRAM EXAMPLE: STRING LITERAL AND STRING VARIABLE CONCATENATION (ADDITION)
>>> # String literal and string variable concatenation Example
>>> planet_name = 'Mars'
>>> distance = ' distance from Sun is 225 kilometers. '
>>> diameter = 'Mars diameter is '

>>> planet_name + distance  + diameter + '6752 kilometers.'
'Mars distance from Sun is 225 kilometers. Mars diameter is 6752 kilometers.'
>>>

Note that this program concatenates three string variables ‘planet_name’, ‘distance’, and ‘diameter’, and one string literal ‘6752 kilometers’.

String Multiplication (Repetition)

We now know how to add (concatenate) string literals and string variables. How about if you want to multiply (repeat) a string multiple times to emphasize what you want to say?

Python can do string multiplication (repetition) using the multiply (*) symbol.

Let us read about planet Mercury facts below and then write a program to show how string multiplication works.

Data Type String Multiplication is explained using Mercury planets facts
Mariner 10

Source: http://www.nasa.gov

Planet Mercury Facts:

Mercury is named after the messenger of the Roman gods, who is also known as Hermes in Greek mythology. This is because of the speed with which Mercury orbits the Sun (one orbit around the Sun is only 87.97 earth-days), and the speed with which Mercury, the Roman deity was able to deliver messages.  Mercury is the second hottest planet after Venus.  Mercury has a very large temperature change, ranging from -170°C (-280°F) during the night to 430°C (800°F) during the day, because Mercury has no atmosphere to regulate temperature.

Mercury Missions

Two spacecraft have ever visited Mercury.  The Mariner 10 visited during 1974-75, flying by Mercury three times and mapping half its surface. In 1974, the Mariner 10 spacecraft captured the first images providing any specific detail of the Mercury’s surface. On March 24, 1975, it ran out of fuel and is still believed to be orbiting the Sun. The MESSENGER probe was launched in 2004 to explore Mercury’s high density, its geological history, the nature of its magnetic field, and more. On March 18, 2011, the MESSENGER spacecraft achieved orbit around Mercury.

MERCURY QUICK FACTS UNITS
Mercury Quick Facts  
Average distance from Sun58Million km
Order from SunFirst 
Orbit duration (length of year) 87.97Earth-days
Rotation period (length of day)58.65 Earth-days
Diameter (km)4879.4km
Maximum surface temperature430°C
Minimum surface temperature -170°C
MERCURY QUICK FACTS

Using the Mercury facts, we will write a program to show how you can use the multiplication (*) symbol to repeat the string any number of times. 

This program combines string multiplication and string addition.

PROGRAM EXAMPLE: STRING MULTIPLICATION (REPETITION)
>>> # String Multiplication Example Program
>>> # Use of multiply (*) symbol to do string repetition
>>> 'Planet Mercury gets ' +5*'very ' + 'cold (-170C) during the night and gets ' +4*'extremely ' + 'hot (430C) during the day' + 3*'!'
'Planet Mercury gets very very very very very cold (-170C) during the night and gets extremely extremely extremely extremely hot (430C) during the day!!!'
>>>

This program repeats (multiplies) the string “very” five times for cold, the string “extremely” 4 times for hot, and the string ‘!’ three times.  String multiplication saves you some typing.

String Indexing

As discussed above, a string is a series of characters. Python numbers these characters in the string starting with 0 for the first character, 1 for the second character, 2 for the third character, and so on. These numbers are called index. Spaces are also characters and are numbered just as characters. Let us explain the concept of string indexing by using planet Venus facts.

PLANET VENUS QUICK FACTS

Venus planet is named for Venus, the Roman goddess of love and beauty. It is the second planet from the Sun.  Venus is also the closest planet to Earth and its size and mass are very similar to earth. Venus’s atmosphere is an opaque layer of clouds formed from sulfuric acid and sulfur dioxide. Venus’s thick, toxic atmosphere traps heat in a ‘greenhouse effect.’

Because of the thick clouds, the surface temperature of Venus is 462°C, hot enough to melt lead. Venus rotates on its axis very slowly, so it takes 243 Earth-days to complete one rotation. The orbit of the planet around the Sun takes 225 Earth-days.  Venus rotates in the opposite direction to other planets. Most other planets rotate counter-clockwise on their axis, however, Venus and Uranus rotate clockwise.

String Data Type Indexing is explained using planet Venus facts
PIONEER SPACE CRAFT FAMILY Source: http://www.nasa.gov

In 1990, the Magellan spacecraft began orbiting Venus. It performed advanced radar image mapping to obtain finer details, similar to that of the Pioneer Venus Orbiter. What Magellan found were approximately 1000 impact craters.

Example of String Indexing

Now, let us explain the concept of the index using planet Venus facts. We define a string variable called ‘planet’ as below. Each character in the string has a number (called an index) associated with it. The table below explains the indexing concept.

>>> planet = ‘venus_temp_462’

Stringvenus_temp_462
Index012345678910111213
INDEXING CONCEPT IN STRINGS

From the table, you can see the first character ‘v’ has an index of ‘0’. The second character ‘e’ has an index of ‘1’, and so on.

Why Use Index

Indexes are useful if you want to select and print a specified character from a string.  For example, if you want to print character ‘s’ in the above string, you would write the following statement:

>>> print(string[4])

In the above statement, ‘4’ is the index of character ‘s’ in ‘venus’.

 The procedure to select and print a few contiguous characters from a string is

  • use the index of the first character to be printed
  • followed by a colon (:)
  • followed by the index of the last character to be printed + 1.

Printing a bunch of contiguous characters in a string is called slicing.

>>> print(string[1:5])

This program will print characters from index 1 to 4.  Note that the last character printed is the one before the last index in the statement. The last index in the statement is never printed.

The program below further explains the concept of string indexing and slicing.

PROGRAM EXAMPLE: INDEXING CONCEPT
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 19:29:22) 
[MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> # String Index and string slicing example.
>>> planet = 'venus_temp_462'
>>> print(planet[4])
s
>>> print(planet[6])
t
>>> # Print a few contiguous characters in string ‘planet’ (Called string slicing).
>>> print(planet[6:10])
temp
>>> # The next statement uses index larger than the string maximum index. Python gracefully handles this.
>>> print(planet[0:20])
venus_temp_462
>>>

Changing Strings

Strings are immutable, that is they cannot be changed.  Any attempt to change a character in the string will cause a syntax error.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Verified by MonsterInsights