Skip to content

Latest commit

 

History

History
245 lines (172 loc) · 7.65 KB

File metadata and controls

245 lines (172 loc) · 7.65 KB

Strings

Strings are perhaps the most important data type in Python. Many other computer languages have strings, and they are used in almost ALL modern programs. Knowing how to manage them, create and modify them to do what you need them to do, is a "sub-superpower" within Python.

Pay close attention; this stuff is VERY important.

What is a String?

Think about the words on this page. The text here is made up of a bunch of letters, and spaces. Now, when we write by hand, we don’t really think about the space between the words, do we? If we truly ignored the notion of space between the words, wewouldendupwithtextlikethis. And while it is possible to read, our modern eyes are trained on well-edited texts; having no spaces tires us pretty quickly.

So yes, what we see as text in this book is really a series of letters and spaces strung together in a line - line after line, paragraph after paragraph. In modern computing, that kind of data is often called a String. It is one of the most fundamental aspects of coding: the manipulation of strings by programs to transform, present or store text in some fashion.

Many programming languages use some kind of quote or double quote to show where strings start and end. There is really no difference between using single or double quotes in Python. So a string like "the quick brown fox" would be a string from the 't' to the 'x'. And notice the three spaces within the string. If they were not there, the string would be "thequickbrownfox". And that’s important, because to the computer, if it keeps these two strings around, it doesn’t really understand that 'the' and 'quick' are just two common English words. The spaces are there to retain more of what the human meant.

No, to the computer, each letter, including the space 'letter', is just a piece of data and very important.

String - a string of letters and numbers and spaces and punctuation, kept altogether for some use. Here are some strings for you to consider.

"the quick brown fox"
"The New York Times"
"And lo, like wave was he..."
"oops"
"Hello, World!"
"supercalifraglisticexpealadocious"
"On sale for $123.99!!"
"Pi is approximately 3.14159"
"Merge left at the ramp to the right, the restaurant is on the right"
'He said, "Wait there is more!"'

Think of strings as a tightly packed list. Each item and letter is numbered. The entire string can be "indexed", meaning I can reach in and copy out, say, the fifth letter easily. String indexes are zero-based; therefore, the first character (element) is in index position 0.

Index  -> 012345
String -> Hello

So here, "H" is at 0, "e" is at 1, 'l' is at 2 & 3, and 'o' is at index position 4. Computers often start numbering things like strings, lists, and arrays at 0, not at one. It’s just one of those things: all strings and arrays (which are coming up) start at zero.

Declaring a string

name = "Wacka Flocka"

Now we have a string variable named name and it’s value is "Wacka Flocka".

String Properties

A common and often used string property is length.

We can use len() builtin function to find the length of a string

motto = "Wakanda Forever!"
answer = len(motto)
print(answer) # -> 16

Accessing Characters in a String

As mentioned before, we can reach into a string and copy out the stuff we find there.

word = "Hello"

# Access the the first character by _indexing_
print(word[0]) # H

# the last character
print(word[len(word) - 1]) # o

When you see something like word[0], it is pronounced like "word sub zero". If you have word[5], you would say "word sub five". This is just verbal shorthand for the expression.

String Concatenation (Joining strings)

This simply means joining strings together using the + operator. We have to turn the 20 (which is a number) into a string. We do this by calling the builtin str() function.

price = 20
dollarSign = "$"
priceTag = dollarSign + str(price) # $20

Or perhaps a little more useful example:

name = "Mikaila"
hoursWorked = str(12)

workReport = "Today, " + name + " worked a total of " + hoursWorked + " hours."
print(workReport)

The output would be:

Today, Mikaila worked a total of 12 hours.

SubStrings

Getting a substring is a common operation. This is how we extract the characters from a string, between two specified indices. (Which is why it’s important to remember the indexes start at 0.) Python offers many ways to substring a string. It is often called ‘slicing’. It follows this pattern:

somestring[start: end: step] and each of the start, end and step indices are optional.

start: The starting index of the substring. The character at this index is included in the substring. If start is not included, it is assumed to equal to 0.

end: The ending index of the substring. The character at this index is NOT included in the substring. If end is not included, or if the value is greater than the string length, it is assumed to be equal to the len() of the string by default.

step:` Every ‘step’ character after the current character to be included. If the step value is not there, Python sets it to 1.

A start position is required, where to begin the extraction (or substring). Remember, first character is at position 0. Characters are extracted from a string between "start" and "end", not including "end" itself.

firstName = "Christopher"

Now let’s use the 3 substring method-functions on firstName and extract and print out "Chris"

firstName = "Christopher"

print(firstName[0:5]) # "Chris"

We took the firstName string and extracted the characters 0 to 4. BUT, let’s try to extract the string "stop" from the name.

firstName = "Christopher"
print(firstName[4:8]) # -> "stop"

Let’s try a little harder idea…​

Tip
firstName = "Christopher"
  • Your turn to use the string slicing on firstName

  • Extract and print out "STOP" from inside the string above

  • And make it uppercase! ("stop" to "STOP") [1]

Well?

firstName = "Christopher"
print(firstName[4:8].upper())

Want to bet there is also a ".lower()" method-function as well?

Summary of substring method-functions

Take a look at these various ways to copy out a substring from the source string named 'rapper', which contains the string 'mikaila'.

rapper = "mikaila"

print(rapper[0:4])  # mika
print(rapper[:4])  # mika
print(rapper[4:])  # ila

print(rapper[1:4])  # ika
print(rapper[1:3]) # ik

How about a few more?

print(rapper[:-2]) # mikai
print(rapper[-2:]) # la
print(rapper[5:]) # la

print(rapper[:]) # mikaila

We’re using a variety of examples to copy out some smaller piece of the 'rapper' string. This is a powerful way to handle strings in Python.

Reverse a String

Now, using the firstName variable again, let’s reverse the string "STOP" to say "POTS".

Tip

To Reverse a String

string = string[::-1]

Whoa. Using defaults as start and end indicates default to 0 and string length respectively and “-1” denotes starting from end and stop at the start, hence reversing string!

print(rapper[::-1]) # aliakim

There are several other means to reverse a string, but this one it most 'pythonic'.

Solution

firstName = "Christopher"
res = firstName[4: 8].upper() # -> "STOP"

rev = res[::-1] # -> POTS
print(rev) # -> POTS

Strings are perhaps the most important data type in almost any language. Being able to manipulate them easily and do powerful things with them in Python, makes you a better coder.


1. You could google how to do this, try "python string make upper case"