Strings
CSCI 1470

by K. Yue

1. String Reviews

Example:

string_basic_1.py: strings are immutable.

#   strings are immutable.
a = 'abcdefgh'
print(f"a: {a}")
print(f"a.upper(): {a.upper()}")
print(f"a: {a}")

#   As a comparison, lists are mutable
list_a = ['a', 'b', 'c']
list_b = list_a
list_c = list(list_a)
print(f"list_a: {list_a}")
print(f"list_b: {list_b}")
print(f"list_c: {list_c}")
print("result = list_a.append('d')")
result = list_a.append('d')
print(f"list_a: {list_a}")
print(f"list_b: {list_b}")
print(f"list_c: {list_c}")
print(f"result: {result}")


2. Iterable index and slice

Example:

string_slice_1.py: assure that you understand the output.

s = "0123456789"
print(f"s: {s}")
print(f"len(s): {len(s)}")

print(f"s[0]: {s[0]}")
print(f"s[1]: {s[1]}")
print(f"s[5]: {s[5]}")
print(f"s[9]: {s[9]}")

print("""
try:
    print(f"s[10]: {s[10]}")
except IndexError:
    print("s[10] out of range")
""")
try:
    print(f"s[10]: {s[10]}")
except IndexError:
    print("s[10] out of range")

print()
print(f"s[1:3]: {s[1:3]}") 
print(f"s[1:]: {s[1:]}")
print(f"s[:3]: {s[:3]}")
print(f"s[1:8:2]: {s[1:8:2]}") 
print(f"s[1::2]: {s[1::2]}") 
print(f"s[::2]: {s[::2]}") 
print(f"s[:7:2]: {s[:7:2]}") 
print(f"s[::-1]: {s[::-1]}")
print(f"s[::-2]: {s[::-2]}")
print(f"s[1:8:-1]: {s[1:8:-1]}")
print(f"s[8:1:-1]: {s[8:1:-1]}")
print(f"s[8:1:-3]: {s[8:1:-3]}")

3. String's Methods

3.1 String Comparisions

Example:

string_comp_1.py:

# unicode
for char in '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
    print(f"ord('{char}'), unicode value: {ord(char)}")
print()
print()

# string comparisons.

a = 'hello'
b = 'Hello'
c = 'Hell'
d = '1234'
e = '57'
f = '553'

print(f"'{a}'=='hello': {a=='hello'}")
print(f"'{a}'!='hello': {a!='hello'}")
print(f"'{a}'>'hello': {a>'hello'}")
print(f"'{a}'>='hello': {a>='hello'}")
print(f"'{a}'<'hello': {a<'hello'}")
print(f"'{a}'<='hello': {a<='hello'}")
print()

print(f"'{b}'=='Hello': {b=='Hello'}")

print()
print(f"'{a}'=='{b}': {a==b}")
print(f"'{a}'!='{b}': {a!=b}")
print(f"'{a}'>'{b}': {a>b}")
print(f"'{a}'>='{b}': {a>=b}")
print(f"'{a}'<'{b}': {a<b}")
print(f"'{a}'<='{b}': {a<=b}")

print()
print(f"'{a}'=='{c}': {a==c}")
print(f"'{a}'!='{c}': {a!=c}")
print(f"'{a}'>'{c}': {a>c}")
print(f"'{a}'>='{c}': {a>=c}")
print(f"'{a}'<'{c}': {a<c}")
print(f"'{a}'<='{c}': {a<=c}")

print()
print(f"'{b}'=='{c}': {b==c}")
print(f"'{b}'!='{c}': {b!=c}")
print(f"'{b}'>'{c}': {b>c}")
print(f"'{b}'>='{c}': {b>=c}")
print(f"'{b}'<'{c}': {b<c}")
print(f"'{b}'<='{c}': {b<=c}")

print()
print(f"'{d}'=='{e}': {d==e}")
print(f"'{d}'!='{e}': {d!=e}")
print(f"'{d}'>'{e}': {d>e}")
print(f"'{d}'>='{e}': {d>=e}")
print(f"'{d}'<'{e}': {d<e}")
print(f"'{d}'<='{e}': {d<=e}")

print()
print(f"'{d}'=='{f}': {d==f}")
print(f"'{d}'!='{f}': {d!=f}")
print(f"'{d}'>'{f}': {d>f}")
print(f"'{d}'>='{f}': {d>=f}")
print(f"'{d}'<'{f}': {d<f}")
print(f"'{d}'<='{f}': {d<=f}")

print()
print(f"'{e}'=='{f}': {e==f}")
print(f"'{e}'!='{f}': {e!=f}")
print(f"'{e}'>'{f}': {e>f}")
print(f"'{e}'>='{f}': {e>=f}")
print(f"'{e}'<'{f}': {e<f}")
print(f"'{e}'<='{f}': {e<=f}")

3.2 Splitting and joining string

Example:

string_split_1.py: Ensure that you understand the output thoroughly.

#  string splitting and joining.

s = "a dog, two dogs and a    cat."
print(f"s: {s}")
print(f"s.split():{s.split()}")
print("The delimiter is not in the result list.")
print("s.split() does not change s.")
print(f"s: {s}")
print(f"s.split('a'):{s.split('a')}")
print(f"s.split('dog'):{s.split('dog')}")
print(f"s.split(maxsplit=-1):{s.split(maxsplit=-1)}")
print(f"s.split(maxsplit=1):{s.split(maxsplit=1)}")
print(f"s.split(maxsplit=2):{s.split(maxsplit=2)}")

print(f"'a man and a woman'.split(): {'a man and a woman'.split()}")
print(f"'a man and a woman'.split('a'): {'a man and a woman'.split('a')}")

s2 = "a 'long' and 'meaningful' journey."
print(f"s2: {s2}")
print(f"s2.split():{s2.split()}")
print("""
print(f"s2.split('\''):{s2.split('\'')}")
produce an error since SyntaxError: f-string expression part cannot include a backslash
""")
result = s2.split("'")
print(f"s2.split(\"'\"): {result}")

sep = "; "
print(f"sep: {sep}")
print(f"sep.join(['cat', 'dog', 'rabbit']): '{sep.join(['cat', 'dog', 'rabbit'])}'")
print(f"sep.join(['cat', 'dog']): '{sep.join(['cat', 'dog'])}'")
print(f"sep.join(['cat']): '{sep.join(['cat'])}'")
print(f"sep.join([]): '{sep.join([])}'")
print(f"','.join(['cat', 'dog', 'rabbit']): '{','.join(['cat', 'dog', 'rabbit'])}'")
print("""
print(f"','.join(['cat', ['dog', 'mouse'], 'rabbit']): '{','.join(['cat', ['dog', 'mouse'], 'rabbit'])}'")
    print(f"','.join(['cat', ['dog', 'mouse'], 'rabbit']): '{','.join(['cat', ['dog', 'mouse'], 'rabbit'])}'")
TypeError: sequence item 1: expected str instance, list found
""")
print("""
print(f"','.join([1,2,3]): '{','.join([1,2,3])}'")
    print(f"','.join([1,2,3]): '{','.join([1,2,3])}'")
TypeError: sequence item 0: expected str instance, int found
""")

3.3 Other string functions


4. Palindrome as an example

Zybooks 7.9 Lab: Palindrome asks you develop code for checking whether a string is a palindrome or not. A palindrome is "a word, phrase, or sequence that reads the same backword as forward." The Lab:

In this classroom demonstrate, we will develop four versions of a palindrome functions using the following skeleton.

palindrome_1_shell.py.txt:

#   ref: Zybooks Chapter 7.9 Lab: Palindrome

#  simple is_palindrome.
def is_palindrome_1(s):
    pass

#   using an alternative method.
def is_palindrome_2(s):
    pass
   
def is_palindrome_3(s):
    #   case insensitive
    pass
   
def is_palindrome_4(s):
    #   case insensitive and remove non-alphabetic characters.
    pass
   
s1 = "racecar"
s2 = "Racecar"
s3 = "Hello world"
s4 = "A Toyota's a Toyota."
print(f"s1: {s1}")
print(f"s2: {s2}")
print(f"s3: {s3}")
print(f"s4: {s4}")

"""
print(f"is_palindrome_1(s1): {is_palindrome_1(s1)}")
print(f"is_palindrome_1(s2): {is_palindrome_1(s2)}")
print(f"is_palindrome_1(s3): {is_palindrome_1(s3)}")
print(f"is_palindrome_1(s4): {is_palindrome_1(s4)}")

print(f"is_palindrome_2(s1): {is_palindrome_2(s1)}")
print(f"is_palindrome_2(s2): {is_palindrome_2(s2)}")
print(f"is_palindrome_2(s3): {is_palindrome_2(s3)}")
print(f"is_palindrome_2(s4): {is_palindrome_2(s4)}")


print(f"is_palindrome_3(s1): {is_palindrome_3(s1)}")
print(f"is_palindrome_3(s2): {is_palindrome_3(s2)}")
print(f"is_palindrome_3(s3): {is_palindrome_3(s3)}")
print(f"is_palindrome_3(s4): {is_palindrome_3(s4)}")   

print(f"is_palindrome_4(s1): {is_palindrome_4(s1)}")
print(f"is_palindrome_4(s2): {is_palindrome_4(s2)}")
print(f"is_palindrome_4(s3): {is_palindrome_4(s3)}")
print(f"is_palindrome_4(s4): {is_palindrome_4(s4)}")  
"""