You are on page 1of 3

Introduction String

March 1, 2024

1 Changing Case in a String with Methods


• .title()
• .upper()
• .lower()

[ ]: string_1 = 'I said, "Python is my favorite language!"'

# Change each word to title case, where each word begins with a capital letter
print(string_1.title())

# Change a string to all uppercase or all lowercase


print(string_1.upper())
print(string_1.lower())

I Said, "Python Is My Favorite Language!"


I SAID, "PYTHON IS MY FAVORITE LANGUAGE!"
i said, "python is my favorite language!"

2 Using Variables in Strings: f-strings


• To insert a variable’s value into a string, place the letter f immediately before the opening
quotation mark.
• Put braces around the name or names of any variable you want to use inside the string.

[ ]: first_name = "Mike"
last_name = "Kuo"
full_name = f"{first_name} {last_name}"
print(full_name)

print(f"Hello, {full_name.upper()}!")

Mike Kuo
Hello, MIKE KUO!

1
3 Adding Whitespace to Strings with Tabs or Newlines
• To add a tab to your text, use the character combination “\t”.
• To add a newline in a string, use the character combination “\n”.
• You can also combine tabs and newlines in a single string. The string “\n\t”.

[ ]: print("Python")
print("\tPython")

Python
Python

[ ]: print("Languages:\nPython\nC\nJavaScript")

Languages:
Python
C
JavaScript

[ ]: print("Languages:\n\tPython\n\tC\n\tJavaScript")

Languages:
Python
C
JavaScript

4 Stripping Whitespace
• .strip()
• .lstrip()
• .rstrip()

[ ]: favorite_language = " python good! "


print(favorite_language)

# To remove the extra space from both sides


print(favorite_language.strip())

# To remove the extra space from the left side


print(favorite_language.lstrip())

# To remove the extra space from the right side


print(favorite_language.rstrip())

python good!
python good!
python good!
python good!

2
However, it is only removed temporarily.
To remove the whitespace from the string permanently, you have to associate the stripped value
with the variable name.

[ ]: favorite_language = " python good! "


print(favorite_language.strip())
print(favorite_language)

favorite_language = favorite_language.strip()
print(favorite_language)

python good!
python good!
python good!

5 Removing Prefixes
• .removeprefix("")

[ ]: # Inside the parentheses, enter the prefix you want to remove.


python_url = "https://www.python.org"
print(python_url.removeprefix('https://'))

www.python.org

References:
• Eric Matthes - Python Crash Course-No Starch Press (2023)

You might also like