Python

Python Menu

To create new, formatted strings, Python utilizes C-style string formatting. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d".

A variable called "name" with the user's name in it, and you would then like to print a greeting to that user.

name = "Mike" print("Hello, %s!" % name)

To use two or more argument specifiers, use a tuple (parentheses):

name = "Jeff" age = 18 print("%s is %d years old." % (name, age))

Any object which is not a string can be formatted using the %s operator as well. The string which returns from the "repr" method of that object is formatted as the string. For example:

my_list = ['skill','talent','job'] print("A list: %s" % my_list)

Here are some basic argument specifiers:

%s - String (or any object with a string representation, like numbers)
%d - Integers
%f - Floating point numbers
%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X - Integers in hex representation (lowercase/uppercase)

Exercise

You will need to write a format string which prints out the data using the following syntax: Hello John Doe. Your current balance is $53.44.

data = ("John", "Doe", 53.44) format_string = "Hello"
print(format_string % data)
data = ("John", "Doe", 53.44) format_string = "Hello %s %s. Your current balance is $%s."
print(format_string % data)
test_object('data') success_msg("Excellent!")

String Operations

To assign the string in these bracket(single quotes are ' ') you need to use double quotes only like this

astring = "Hello world!"
print("single quotes are ' '") print(astring)

String length can be obtained using the len() function

astring = "Hello world!"
print(len(astring))

It printed out 12, because "Hello world!" is 12 characters long, including punctuation and spaces.

astring = "Hello world!" print(astring.index("o"))

That prints out 4, because the location of the first occurrence of the letter "o" is 4 characters away from the first character. Notice how there are actually two o's in the phrase - this method only recognizes the first.

But why didn't it print out 5? Isn't "o" the fifth character in the string? To make things more simple, Python (and most other programming languages) start things at 0 instead of 1. So the index of "o" is 4.

astring = "Hello world!" print(astring.count("l"))

This counts the number of l's in the string. Therefore, it should print 3.

astring = "Hello world!" print(astring[3:7])

This prints a slice of the string, starting at index 3, and ending at index 6. But why 6 and not 7? Again, most programming languages do this - it makes doing math inside those brackets easier.

If you just have one number in the brackets, it will give you the single character at that index. If you leave out the first number but keep the colon, it will give you a slice from the start to the number you left in. If you leave out the second number, it will give you a slice from the first number to the end.

You can even put negative numbers inside the brackets. They are an easy way of starting at the end of the string instead of the beginning. This way, -3 means "3rd character from the end".

astring = "Hello world!" print(astring[3:7:2])

This prints the characters of string from 3 to 7 skipping one character. This is extended slice syntax. The general form is [start:stop:step].

astring = "Hello world!" print(astring[3:7]) print(astring[3:7:1])

Both of them produce same output

There is no function like strrev in C to reverse a string. But with the above mentioned type of slice syntax you can easily reverse a string like this

astring = "Hello world!" print(astring[::-1])

upper() and lower() functions

These make a new string with all letters converted to uppercase and lowercase, respectively.

astring = "Hello world!" print(astring.upper()) print(astring.lower())

startswith() and endswith() functions

This is used to determine whether the string starts with something or ends with something, respectively. The first one will print True, as the string starts with "Hello". The second one will print False, as the string certainly does not end with "foo".

astring = "Hello world!" print(astring.startswith("Hello")) print(astring.endswith("foo"))

split() function

This splits the string into a bunch of strings grouped together in a list. Since this example splits at a space, the first item in the list will be "Hello", and the second will be "world!".

astring = "Hello world!" afewwords = astring.split(" ")

Exercise

Try to fix the code to print out the correct information by changing the string.

s = "Hello and Good day!" # Length should be 20 print("Length of s = %d" % len(s))
# First occurrence of "a" should be at index 8 print("The first occurrence of the letter a = %d" % s.index("a"))
# Number of a's should be 2 print("a occurs %d times" % s.count("a"))
# Slicing the string into bits print("The first five characters are '%s'" % s[:5]) # Start to 5 print("The next five characters are '%s'" % s[5:10]) # 5 to 10 print("The thirteenth character is '%s'" % s[12]) # Just number 12 print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing) print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end
# Convert everything to uppercase print("String in uppercase: %s" % s.upper())
# Convert everything to lowercase print("String in lowercase: %s" % s.lower())
# Check how a string starts if s.startswith("Str"): print("String starts with 'Str'. Good!")
# Check how a string ends if s.endswith("ome!"): print("String ends with 'ome!'. Good!")
# Split the string into three separate strings, # each containing only a word print("Split the words of the string: %s" % s.split(" "))
s = "Strings are awesome!" # Length should be 20 print("Length of s = %d" % len(s))
# First occurrence of "a" should be at index 8 print("The first occurrence of the letter a = %d" % s.index("a"))
# Number of a's should be 2 print("a occurs %d times" % s.count("a"))
# Slicing the string into bits print("The first five characters are '%s'" % s[:5]) # Start to 5 print("The next five characters are '%s'" % s[5:10]) # 5 to 10 print("The thirteenth character is '%s'" % s[12]) # Just number 12 print("The characters with odd index are '%s'" %s[1::2]) #(0-based indexing) print("The last five characters are '%s'" % s[-5:]) # 5th-from-last to end
# Convert everything to uppercase print("String in uppercase: %s" % s.upper())
# Convert everything to lowercase print("String in lowercase: %s" % s.lower())
# Check how a string starts if s.startswith("Str"): print("String starts with 'Str'. Good!")
# Check how a string ends if s.endswith("ome!"): print("String ends with 'ome!'. Good!")
# Split the string into three separate strings, # each containing only a word print("Split the words of the string: %s" % s.split(" "))
test_output_contains("Length of s = 20") test_output_contains("The first occurrence of the letter a = 8") test_output_contains("a occurs 2 times") test_output_contains("String starts with 'Str'. Good!") test_output_contains("String ends with 'ome!'. Good!") success_msg("Excellent!")

Introduction

Python Basics

Python Advance

Data Science Python Tutorials

Python Functions and Methods