Python Tutorials

Overview

In Python, strings are surrounded by either single quotation marks, or double quotation marks. “Hello World” is the same as ‘Hello World’.

Quotes can be inside a string, as long as they don’t match the quotes surrounding the string.

x = "It's a nice day"
y = "His name is 'Johnny'"
z = 'His name is "Johnny"'

Multiline Strings

You can assign a multiline string to a variable by using three double quotes or three single quotes.

x = """Chickens, ducks,
cows, and donkeys,
dancing on the nearby farm."""

y = '''Chickens, ducks,
cows, and donkeys,
dancing on the nearby farm.'''

Note

Line breaks are inserted at the same position as in the code.

Strings are Arrays

Strings in Python are arrays of characters. Square brackets can be used to access specific elements of the string.

a = "Hello World"
print(a[6])

Output:

W

Note

Arrays count starting from zero NOT one. So item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on.

Strings can be looped through the characters in a string, with a for loop

for x in "chicken":
    print(x)

Output:

c
h
i
c
k
e
n

Getting the String Length

To get the length of a string, use the len() function.

x = "Hello World"
print(len(x))

Output:

11

Checking if a Phrase or Character is in a String

txt = "Chickens are cute and friendly."
print("cute" in txt)

Output:

True

Checking if a Phrase or Character is NOT in a String

txt = "Chickens are cute and friendly."
print("cute" not in txt)

Output:

False

Python Notes:

  • The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
  • Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
  • Python string methods return new values, and DO NOT change the original string

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.