๐ The One with Python Strings ๐#
๐ต Iโll Be There for You! ๐ต#
โSo no one told you life was gonna be this wayโฆโ ๐ ๐ ๐ ๐ ๐ ๐
But with strings, youโll always have a friend in Python!
๐บ What Are Strings?#
Strings are sequences of charactersโPythonโs way of storing text. Theyโre as essential to coding as Joeyโs sandwiches ๐ or Monicaโs cleaning obsession ๐งฝ.
quote = "We were on a break!"
episode = "The One Where Ross Learns Strings"
Strings in Python:#
Use single (
'
) or double ("
) quotes. Python is flexible like Ross pivoting a couch ๐.Represent text data, such as names, phrases, or emojis! ๐
๐ Multiline Strings#
For long blocks of text like Phoebeโs songs or Rossโs dinosaur facts, use triple quotes ('''
or """
).
phoebe_song = """Smelly Cat, Smelly Cat,
What are they feeding you?
Smelly Cat, Smelly Cat,
It's not your fault."""
print(phoebe_song)
Smelly Cat, Smelly Cat,
What are they feeding you?
Smelly Cat, Smelly Cat,
It's not your fault.
๐ String Operations: Manipulating Like Chandlerโs Sarcasm#
Concatenation#
Combine strings using the +
operator, like Chandler combining sarcasm and wit.
chandler = "Could I " + "BE " + "any more excited?"
print(chandler)
Could I BE any more excited?
๐ Repetition#
Repeat strings with the *
operator, just like Joey repeating, โHow you doinโ?โ
joey = "Pizza! " * 3
print(joey) # Pizza! Pizza! Pizza!
Pizza! Pizza! Pizza!
๐ข Length#
Count characters in a string using len()
.
rachel = "Fashion Icon"
print(len(rachel)) # 12
12
๐ Indexing and Slicing#
Strings are like Rachelโs wardrobeโwell-organized and accessible.
๐ท Indexing#
Access specific characters by position.
Python uses zero-based indexing, so the first character is at index
0
.The first index is inclusive, and the last index is exclusive. Meaning
s[2:5]
includes characters at indices2
,3
, and4
, but not5
.
monica = "Organized"
print(monica[0]) # O
print(monica[-1]) # d
O
d
Negative indexing starts from the end of the string.
โ๏ธ Slicing#
Extract subsets of strings, like picking the best parts of Rossโs lectures.
ross = "Dinosaurs are cool"
print(ross[0:9]) # Dinosaurs
print(ross[-4:]) # cool
Dinosaurs
cool
๐ญ String Methods: Superpowers for Strings#
Python strings come with many methodsโthink of them as Phoebeโs quirky talents ๐ธ.
๐ก Change Case#
Manipulate the case of strings:
ross = "Dinosaurs are cool"
print(ross.upper()) # DINOSAURS ARE COOL
print(ross.lower()) # dinosaurs are cool
print(ross.capitalize()) # Dinosaurs are cool
print(ross.title()) # Dinosaurs Are Cool
DINOSAURS ARE COOL
dinosaurs are cool
Dinosaurs are cool
Dinosaurs Are Cool
.upper()
: Converts all characters to uppercase..lower()
: Converts all characters to lowercase..capitalize()
: Capitalizes the first letter of the string..title()
: Capitalizes the first letter of each word.
๐ Search and Find#
Locate specific text within strings:
chandler = "Could I BE any more sarcastic?"
print(chandler.find("BE")) # 8
print(chandler.index("sarcastic")) # 21
8
20
.find()
: Returns the index of the first occurrence of the substring or-1
if not found..index()
: Same as.find()
, but raises an error if the substring isnโt found.
๐ง Replace Text#
Replace parts of a string, like swapping Joeyโs sandwiches for pizza.
joey = "I love sandwiches."
print(joey.replace("sandwiches", "pizza")) # I love pizza.
I love pizza.
โ Check String Contents#
Check if a string contains specific types of characters:
rachel = "123Fashion"
print(rachel.isalpha()) # False (contains digits)
print(rachel.isdigit()) # False (contains letters)
print(rachel.isalnum()) # True (letters and digits only)
print(" ".isspace()) # True (only spaces)
False
False
True
True
๐งน Stripping Whitespace#
Remove extra spaces, like Monica cleaning crumbs off the counter.
messy = " Clean me up! "
print(messy.strip()) # Removes leading and trailing spaces
print(messy.lstrip()) # Removes leading spaces
print(messy.rstrip()) # Removes trailing spaces
Clean me up!
Clean me up!
Clean me up!
โ๏ธ Split and Join#
Break strings into lists or combine lists into strings.
ross_quote = "Dinosaurs, Paleontology, Fossils"
print(ross_quote.split(", ")) # ['Dinosaurs', 'Paleontology', 'Fossils']
friends = ["Rachel", "Ross", "Joey", "Chandler"]
print(", ".join(friends)) # Rachel, Ross, Joey, Chandler'
['Dinosaurs', 'Paleontology', 'Fossils']
Rachel, Ross, Joey, Chandler
๐ Advanced Formatting#
f-Strings#
Format strings dynamically with f-strings
.
F-strings in Python are a concise way to embed expressions inside string literals, using the syntax f"..."
. An f-string allows you to directly evaluate expressions within the string, improving readability and reducing the need for string concatenation or manual formatting.
Syntax
variable = 10
f"Value is {variable}"
This will evaluate `variable` and output: `"Value is 10"`.
Key Points:#
Prefix with
f
: The string starts with anf
(orF
) before the opening quote.Curly braces
{}
: Expressions inside curly braces are evaluated at runtime, and their result is inserted into the string.Any expression: You can include variables, arithmetic, function calls, and more inside the curly braces.
name = "Joey"
food = "pizza"
print(f"{name} loves {food}.")
Joey loves pizza.
๐ง Formatting Numbers#
Format numbers neatly, like Monica tallying up her perfect cooking scores.
Using F-strings#
F-strings allow you to format numbers with a wide variety of options, such as specifying the number of decimal places, alignment, width, and more.
Syntax
Hereโs how you format numbers in Python:
number = 1234.5678
f"{number:.2f}" # Formats the number to two decimal places
Output:
"1234.57"
Key Formatting Options:#
Precision:
:.2f
formats the number to 2 decimal places.Width:
{number:10.2f}
formats the number with a width of 10 characters, padded with spaces.Commas:
{number:,.2f}
formats the number with commas separating thousands.
Using str.format()
Method#
You can also format numbers using the str.format()
method, which provides similar functionality to f-strings but requires extra syntax.
Syntax
number = 1234.5678
"{:.2f}".format(number)
This outputs:
"1234.57"
Using format()
Function#
The format()
function is another way to format numbers, allowing for similar formatting options.
Syntax
number = 1234567.89
format(number, ",.2f") # Formats number with commas and two decimal places
This outputs:
"1,234,567.89"
score = 95.6789
print(f"Score: {score:.2f}") # Score: 95.68
Score: 95.68
๐ Real-World Applications#
Data Cleaning: Tidy up messy data like Monica organizes her apartment ๐งผ.
Web Scraping: Extract data for Rachelโs fashion blog ๐.
Text Analytics: Analyze Rossโs long emails for paleontology buzzwords ๐ฆ.
And donโt forget, strings in Python are as dynamic as the Friends crew:
Combine like Joey and sandwiches:
"Pizza" + " is life!"
Extract like Ross in a museum:
ross[:10]
gives you"Dinosaurs"
Shout like Monica cleaning:
monica.upper()
Transform like Rachelโs hairstyles:
quote.replace("break", "coding adventure")
Python strings will always BE there for you! ๐