Pure Programmer
Blue Matrix


Cluster Map

Strings

L1

This page is under construction. Please come back later.

At their heart, a string is simply a sequence of characters. Characters, in turn, are encoded as integers using encoding schemes such as [[ASCII]], [[ISO-Latin-1]] or [[Unicode]]. So a string is simply a sequence of integers. Languages like FORTRAN or C that don't support strings as a fundamental type, actually treat strings as a sequence of integers. Modern programming languages support strings as a fundamental data type which make them much easier to use and manipulate.

Strings are particularly useful when conveying information to the user in contrast to being useful for computation like integers or floating point values. While strings are typically implemented as an array/list of the more basic character type, modern languages provide a string data type that encapsulates the characters of a string and provide functionality for working with strings. When using strings in our programs there are two types of strings: [[literal]] strings and string variables.

Variables and Literals

String literals are string values that are directly written in the program itself. String literals only represent the one string as it is typed into the code. String literals are enclosed in double quotes or single quotes. String literals can be used any place a string is required.

"Hello, world!"
"My name is: "
'Four score and seven years ago...'
'z'

Example String Literals

String variables are like any other variable. This means that string variables must be declared before they can be used and must follow the variable naming rules discussed in the variables section. that is they can be set and reset to different values at will. Unlike variables of the primitive types such as boolean, integer and floating point, string variables represent an entire string of characters. String variables can be set using string literals or other string variables.

Concatenation

One of the most basic operations we can perform on strings is called concatenation. Concatenation takes two strings and forms a new one by appending the second string on to the end of the first string. Using concatenation we can build up a complex string from small strings. In Python the concatenation operator is the + (plus) symbol.

Strings1.py
#!/usr/bin/env python3;
###############################################################################
# This program demonstrates string concatenation.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

# Begin Main
a = "one"
b = "two"
c = "three"
d = a + b + c
print(d)
d = a + "\t" + b + "\n" + c
print(d)

Output
$ python3 Strings1.py onetwothree one two three

Operations on Strings

Python supports a number of operations on strings. The most often used is determining the length of a string. [an error occurred while processing this directive] Counting the characters in a string is accomplished using the length() method. Some of the other string operations available are summarized in the following table.

String Operations
Fixed PointScientific Notation
00e0
3.14153.1415e0
Strings2.py
#!/usr/bin/env python3;
###############################################################################
# This program demonstrates basic string functions.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

# Begin Main
alphabet = "abcdefghijklmnopqrstuvwxyzabc"
greekAlphabet = "αβγδεζηθικλμνξοπρσςτυφχψωαβγ"
emoji = "😃😇🥰🤪🤑😴🤒🥵🥶🤯🥳😎😥😱😡🤬💀👽🤖😺🙈🙉🙊😃😇🥰"

print("Length: " + str(len(alphabet)))
print("charAt(17): " + str(alphabet[17]))
print("codePointAt(17): " + str(ord(alphabet[17])))
print("substr(23, 26): " + alphabet[23:26])
print("prefix(6): " + alphabet[0:6])
print("right_tail(6): " + alphabet[6:])
print("suffix(6): " + alphabet[len(alphabet) - 6:])
print("find(\'def\'): " + str(alphabet.find("def")))
print("find(\'def\') is not found: " + str((alphabet.find("def") == -1)))
print("find(\'bug\'): " + str(alphabet.find("bug")))
print("find(\'bug\') is not found: " + str((alphabet.find("bug") == -1)))
print("rfind(\'abc\'): " + str(alphabet.rfind("abc")))
print("rfind(\'abc\') is not found: " + str((alphabet.rfind("abc") == -1)))
print("rfind(\'bug\'): " + str(alphabet.rfind("bug")))
print("rfind(\'bug\') is not found: " + str((alphabet.rfind("bug") == -1)))

print("Length: " + str(len(greekAlphabet)))
print("charAt(17): " + str(greekAlphabet[17]))
print("codePointAt(17): " + str(ord(greekAlphabet[17])))
print("substr(23, 26): " + greekAlphabet[23:26])
print("prefix(6): " + greekAlphabet[0:6])
print("right_tail(6): " + greekAlphabet[6:])
print("suffix(6): " + greekAlphabet[len(greekAlphabet) - 6:])
print("find(\'δεζ\'): " + str(greekAlphabet.find("δεζ")))
print("find(\'δεζ\') is not found: " + str((greekAlphabet.find("δεζ") == -1)))
print("find(\'bug\'): " + str(greekAlphabet.find("bug")))
print("find(\'bug\') is not found: " + str((greekAlphabet.find("bug") == -1)))
print("rfind(\'αβγ\'): " + str(greekAlphabet.rfind("αβγ")))
print("rfind(\'αβγ\') is not found: " + str((greekAlphabet.rfind("αβγ") == -1)))
print("rfind(\'bug\'): " + str(greekAlphabet.rfind("bug")))
print("rfind(\'bug\') is not found: " + str((greekAlphabet.rfind("bug") == -1)))

print("Length: " + str(len(emoji)))
print("charAt(16): " + str(emoji[16]))
print("codePointAt(16): " + str(ord(emoji[16])))
print("substr(20, 24): " + emoji[20:24])
print("prefix(6): " + emoji[0:6])
print("right_tail(6): " + emoji[6:])
print("suffix(6): " + emoji[len(emoji) - 6:])
print("find(\'😱😡🤬\'): " + str(emoji.find("😱😡🤬")))
print("find(\'😱😡🤬\') is not found: " + str((emoji.find("😱😡🤬") == -1)))
print("find(\'bug\'): " + str(emoji.find("bug")))
print("find(\'bug\') is not found: " + str((emoji.find("bug") == -1)))
print("rfind(\'😃😇🥰\'): " + str(emoji.rfind("😃😇🥰")))
print("rfind(\'😃😇🥰\') is not found: " + str((emoji.rfind("😃😇🥰") == -1)))
print("rfind(\'bug\'): " + str(emoji.rfind("bug")))
print("rfind(\'bug\') is not found: " + str((emoji.rfind("bug") == -1)))

Output
$ python3 Strings2.py Length: 29 charAt(17): r codePointAt(17): 114 substr(23, 26): xyz prefix(6): abcdef right_tail(6): ghijklmnopqrstuvwxyzabc suffix(6): xyzabc find('def'): 3 find('def') is not found: False find('bug'): -1 find('bug') is not found: True rfind('abc'): 26 rfind('abc') is not found: False rfind('bug'): -1 rfind('bug') is not found: True Length: 28 charAt(17): σ codePointAt(17): 963 substr(23, 26): ψωα prefix(6): αβγδεζ right_tail(6): ηθικλμνξοπρσςτυφχψωαβγ suffix(6): χψωαβγ find('δεζ'): 3 find('δεζ') is not found: False find('bug'): -1 find('bug') is not found: True rfind('αβγ'): 25 rfind('αβγ') is not found: False rfind('bug'): -1 rfind('bug') is not found: True Length: 26 charAt(16): 💀 codePointAt(16): 128128 substr(20, 24): 🙈🙉🙊😃 prefix(6): 😃😇🥰🤪🤑😴 right_tail(6): 🤒🥵🥶🤯🥳😎😥😱😡🤬💀👽🤖😺🙈🙉🙊😃😇🥰 suffix(6): 🙈🙉🙊😃😇🥰 find('😱😡🤬'): 13 find('😱😡🤬') is not found: False find('bug'): -1 find('bug') is not found: True rfind('😃😇🥰'): 23 rfind('😃😇🥰') is not found: False rfind('bug'): -1 rfind('bug') is not found: True

Comparing Strings

Like numeric types, string types are comparable. This means that we can order strings and determine which ones are lower and which ones are higher in that ordering. Strings are ordered using [[Lexicographical Order]] also know as Alphabetic or Dictionary Order. This is done by comparing the first characters of the two strings to determine which string is lower and which is higher. If the first characters are the same, we move on to the second character in each string and so on until a difference is found. Shorter strings always compare lower than a longer string that has the lower string as its prefix. Like numeric types, we have six comparison operators that allow us to determine how two strings compare lexicographically.

String Comparison Operators
OperatorMeaning
==equal to
!=not equal to
<less than
<=less than or equal
>greater than
>=greater than or equal
Strings3.py
#!/usr/bin/env python3;
###############################################################################
# This program demonstrates string comparisons.
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

import Utils

# Begin Main
color1 = "Blue"
color2 = "Red"

print("compare(color1, color2): " + str(Utils.compareTo(color1, color2)))
result = color1 < color2
print("color1 < color2: " + str(result))
result = color1 > color2
print("color1 > color2: " + str(result))
result = color1 == color2
print("color1 == color2: " + str(result))
result = color1 != color2
print("color1 != color2: " + str(result))

Output
$ python3 Strings3.py compare(color1, color2): -1 color1 < color2: True color1 > color2: False color1 == color2: False color1 != color2: True

Character Types

Often it is necessary to determine what class an individual character belongs. Character classes such as alphabetic, numeric, whitespace, control and punctuation are common classes of characters in which we would be interested. The following table illustrates how we would determine the class of a character.

Strings4.py
#!/usr/bin/env python3;
###############################################################################
# This program illustrates some of the string functions in Utils
# 
# Copyright © 2020 Richard Lesh.  All rights reserved.
###############################################################################

import Utils

ltrstr = "   Spaces to the left"
rtrstr = "Spaces to the right  "
trimstr = "   Spaces at each end   "
blank = "  \t\n  "
lowerstr = "This String is Lowercase"
upperstr = "This String is Uppercase"

# Begin Main
print(str("|") + ltrstr.lstrip() + str("|"))
print(str("|") + rtrstr.rstrip() + str("|"))
print(str("|") + trimstr.strip() + str("|"))
print(str("|") + blank.strip() + str("|"))
print(str("|") + lowerstr.lower() + str("|"))
print(str("|") + upperstr.upper() + str("|"))


Output
$ python3 Strings4.py |Spaces to the left| |Spaces to the right| |Spaces at each end| || |this string is lowercase| |THIS STRING IS UPPERCASE|
Character Classification
FunctionDescription
isalnum(c)Check if character is alphanumeric.
isalpha(c)Check if character is alphabetic.
isblank(c)Check if character is blank.
iscntrl(c)Check if character is a control character.
isdigit(c)Check if character is decimal digit.
isgraph(c)Check if character has graphical representation.
islower(c)Check if character is lowercase letter.
isprint(c)Check if character is printable.
ispunct(c)Check if character is a punctuation character.
isspace(c)Check if character is a white-space.
isupper(c)Check if character is uppercase letter.
isxdigit(c)Check if character is hexadecimal digit.

Character Conversion
FunctionDescription
tolower(c)Returns lowercase version of the character.
toupper(c)Returns uppercase version of the character.
python

Questions

Projects

More ★'s indicate higher difficulty level.

References