๐Ÿ“– 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!

Friends Theme

๐Ÿ“บ 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 indices 2, 3, and 4, but not 5.

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:#

  1. Prefix with f: The string starts with an f (or F) before the opening quote.

  2. Curly braces {}: Expressions inside curly braces are evaluated at runtime, and their result is inserted into the string.

  3. 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! ๐ŸŽ‰