At the end of this lesson, you will be able to:
be able to manipulate strings
review module importing
The String (str) data type has many features, and can be manipulated in many different ways. Strings, a collection of characters, take up the most memory space of any variable, and are among the most common and useful variables in programming. There are a number of features that are available to manipulate the size of the string, the contents of the string, accept a user's input as a string, convert the content of a string to other data types and even to combine, remove or find portions of strings within other strings.
ASCII Characters
These characters in a string are treated as numbers (ASCII numbers) by the computer. As seen in the CS Circles tutorials, ASCII Characters are a set of characters that are available on most computers by deliberate design. ASCII stands for American Standard Code for Information Interchange. There are 256 predefined ASCII characters, 128 of which are used for standard characters.. Each character is represented by a decimal number from 0 to 255. A listing of these characters can be found at https://www.ascii-code.com/. A look at this table will quickly reveal that there are more characters than are regularly used. It will also reveal that the capital or uppercase letters have different codes than the lowercase ones.
ASCII characters that are not on the keyboard can be displayed by using the chr(characterNumber) command. One way to use this command is with aprint() statement. For example:
print(chr(214) + " " + chr(214))
will display
Ö Ö
Note that the chr() command must be used with a print() statement or assigned to string variable. In other words, you can create a string variable called wordthat would contain a single character "Ö"
word = chr(214)
The ASCII number of a character can be obtained using the function ord(character). ASCII values are integers so the results of the function ord() can also be stored in an int. So given the int variable asciiNum, this command will store the value 35 in asciiNum.
asciiNum = ord("#")
The older version of the ASCII character set allowed the use of characters to create lines. While this aided in creating simple animations for early programs, the modern, Windows based sets, hold multilingual characters that are more valuable in the widely used computer environments of today.
Length of a String
The number of characters in any string can be found using a the function len(). The function len() returns an int, which can be assigned to a variable or used where a number is expected, such as a print statement or a for loop. The following are examples of these usages:
# Example 1
# len is assigned to a variable
word = input("Enter a word: ") # input
howLong = len(word)
print ("The word, " + word + ", is", howLong, "characters long.")
# Example 2
# len is used in a print statement
word = input("Enter a word: ") # input
print ("The word, " + word + ", is", len(word), "characters long.")
String Arithmetic
Strings can be added on to other strings. This process is called concatenation. Given the string variables str1, str2, str3, str4, where str1= "This", str2= "is", and str3= "a test." the string str4 can be assigned using the following command:
str4 = str1 + " " + str2 + " " + str3
Typing print(str4) will output This is a test.
This is similar to the way output can be controlled in the print() statements, however, you cannot add other data types into a string without converting them first. The advantage to using this is that a string can be assembled from parts and output in a single variable. Also, a string can be assembled from parts of other strings.
The following program demonstrates some of the string functions introduced so far:
Partial Strings
Accessing partial strings from a string variable is the ability to access one or more characters from the contents of a string variable. Python treats strings as a set of characters, with an internal index for each character. Each string character is known by its location in the string. Using the string variable str4 from the String Arithmetic example we could visualize the string as follows:
str4 T h i s i s a t e s t .
index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Any character in the string variable can be accessed by writing its index number in square brackets after the variable name. In a print statement, this might look like: print(str4[0]). The output would be "T". The statement print(str4[12]) would output "s".
To create partial strings indicate the part of the string to be outputted in brackets using a colon between the first and last index numbers of the sub-string. For example, with the string variable str4 used in the string arithmetic example, the code: print(str4[0:6]). would output "This i" To access the last character you can use len(str4). For example print(str4[8:len(str4)] would output: "a test."
Comparing Strings
Python treats strings in a special way when used in a comparison statement like a while condition. The evaluation of characters is not based on the letters, or on any combination of the letters. Rather, the letters are each treated as individual numbers using their ASCII codes. Thus it is possible to compare strings using > and < operators.
Python compares the character in index 0 in each word, then the character in index 1, then index 2, and so on, until the comparison fails. The rest of the word is ignored.
To observe how this works, try copying the following code into Eclipse. Then, try changing the values of str1 and str2 to gain a better understanding of string comparison.
Find
The str.find(str) function allows the programmer to search a string for a certain pattern in a string. The function will return the first index location where the pattern exists. For example, the code:
location = word.find("at")
will result in a value of 1 being placed in location.
Please accept this Github Classroom Assignment.
Create a program that will accept a word from a user and return the length of that word. Make this program in a loop with option to exit when the use types in quit. Name the program Q1Length.py.
Create a program that will accept a word and output the word one letter at a time in reverse. Name the program Q2Reverse.py
Create a program that will prompt the user for a word, and return a 'word triangle'. For example, if the user types in the word "PYTHON", your program will output:
P
PY
PYT
PYTH
PYTHO
PYTHON
Name the program Q3WordTriangle.py.
work on weekly assignment