0% found this document useful (0 votes)
7 views5 pages

02.05 Strings

The document explains the concept of strings in Python, highlighting that they are treated as arrays of characters but are immutable. It covers string manipulation techniques, methods, and comparisons, including how to use relational operators and Unicode values. Additionally, it provides exercises for practicing string manipulation skills.

Uploaded by

Jukeonyou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views5 pages

02.05 Strings

The document explains the concept of strings in Python, highlighting that they are treated as arrays of characters but are immutable. It covers string manipulation techniques, methods, and comparisons, including how to use relational operators and Unicode values. Additionally, it provides exercises for practicing string manipulation skills.

Uploaded by

Jukeonyou
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Strings

In general programming terms, strings are likened to arrays of characters. Python, strictly speaking, does
not have a char simple data type – it considers values of 1 character as a string of length 1. For purposes
of the course, the distinction is not important.

However, important to note is that strings are manipulated like lists. Each character (in a physical sense,
not data type sense) of a string is manipulated as an element in a list.
For example,

x = “Hippo” can be thought of as in an array with an H i p p o


index 0 1 2 3 4

And the characters referenced by the index.

Try x = “Hippo”
print (x[0])

print ( x[3:]) #You can “slice” strings

print (len (x)) #And len() can be used to determine the length of a string

But strings are not strictly arrays – there are differences.

Try y = [“H”, “i”, “p”, “p”, “o”]


print (x)
print (y)

y.append (“campus”) # the “hippocampus” is part of the brain

Note that the printed output does not have the square brackets in this case.
Also note that trying to append a new element to a string, as we would do to add to a list, causes a run
time error.

Further, string arrays cannot be changed via the indices

x [0] = “P”

Strings share many characteristics as lists but cannot be changed. They are immutable. Python has
several things that have similar in some ways (like lists and strings) but have changeable (mutable), and
not changeable (immutable) versions.

If a string needed to be manipulated, Python requires that you create a new string.

x = “Bear”
y = “P” + x[1:] #Recall “+” means concatenation when used with strings, not addition
print (x, “ “, y)
String has many associated functions (or specifically “methods”) that can be called for more specific
string manipulating.
For example, <string_identifier>.upper()

Try
x = “Satec rocks”
print(x.upper() ) #Notice the dot operator “.” is used

print(“sandwich”.upper()) #Well, isn’t that interesting!

The following is a partial list of useful-to-this-course string methods:

capitalize center endswith find(search_element)


isalnum isalpha isdigit islower
isupper isspace join lower
upper swapcase count(search_element)
replace(element, replacement[, number])
split sort

Comparing strings

Strings can be used in relational operators. In other words, “is this string equal to another?” or “is this
string greater than another?” are valid questions to ask.

Recall that characters are represented in the Unicode table

https://www.unicode.org/charts/

The basic ASCII set can be found in the Scripts section, under Latin, as Basic Latin (ASCII).

Every character has a decimal value. When comparing strings, the strings are compared character by
character by their decimal value in index order (ie from the front of the word to the back).

Knowing that characters have numerical equivalences, it is easy to understand that each of the following
relational expressions evaluate to True.

“eat” == “eat”
“eat” != “food”

“eat” < “sleep” #”e” is less than “s” so “eat” is less than “sleep”

“eaten” < “eats” #The words compare equally until the first letter that is different.
#Then “e” is less than “s”

“eat” < “eaten” #Similar to above, but “eaten” has extra characters so is greater in value
There are some functions that allow programs to switch between characters and their Unicode values.
ord() returns the Unicode number of a character (in decimal). So “E” is less than “e”.

Try print (ord(“e”) )


print (ord(“E”) )
print (ord(“#”) )

chr() does the reverse. Given a Unicode number in decimal, it returns the character the number
represents.

Try
print (chr (71))
Exercises with Strings

String methods can be used if appropriate. You may have to look up what a particular method does to
see if it suites your needs.

1) Write a program that accepts a string, then accepts from the user a number, n. Create a new string
made out of the first n letters concatenated to the last n letters. Print out the new word. If the
number is greater than the number of letters in the string, then print an appropriate message.
Eg Enter a word: chimera
Enter a slice size : 5
Your slice is chimeimera

2) Write a program to accept several sentences, with periods, as a single input. Have the program
insert “, eh?” in front of each period. Print the results.

3) Write a program that accepts a sentence as 1 input. The program then changes all cases of “him”
and “her” to “them”, all cases of “he” and “she” to “they”. Print out the updated sentence.

4) Write a program that encodes and decodes a string. Prompt the user whether they want to encode
or decode input.
To encode, take each character of a string, and change it to the character 2 greater above according
to the Unicode table. ie. “e” changes to “g”. Print out the encoded string.
To decode, take a given string and do the reverse of the above.
Test your program by encoding a string, then use your program to decode it.

5) Write a program that will take a string and return the different unique characters in the string, along
with the number of occurrences of each character in the string, from the most used to the least. If
there is a tie among different characters, no need to sort the characters further. Capitalization
counts (ie “A” is a different character than “a”).

For example, “I like pizzas and panzerottos.” will result in


4 <- note a space just prints as a blank space
a 3
z 3
s 2
:
I 1
. 1

6) Simple Palindrome
A palindrome is a word that is has the same spelling forward and backward eg madam or racecar. Write
a program that accepts one letter at a time, and which stops receiving input when the user has entered
letters that make up a palindrome or when the user does not enter a letter but just presses Enter.
Note: A program checks for a user entering nothing by comparing to “” (ie two double apostrophes with
nothing between them).

Capitalization counts eg Madam is not a palindrome.

eg.
Enter a letter: R
Enter a letter: A
Enter a letter:D
Enter a letter: A
Enter a letter:R

You have entered the palindrome RADAR

eg.Enter a letter: R
Enter a letter: A
Enter a letter:D
Enter a letter: A
Enter a letter:A
Enter a letter: <- nothing was entered

RADAA is not a palindrome

You might also like