Objectives

Students will be able to:

  • write come to process strings in Python

STRINGS

Data processed by computers is often text. The datatype for text is known as STRING.

Here is a STRING stored in a variable in Python:

word = "Hello!"

Processing strings is what computers do a lot of! Python is a king at processing strings!

print(f"{word.lower()}") output = hello!

print(f"{word.upper()}") output = HELLO!

print(f"{word[0]}") output = h

print(f"{word[0:2]}") output = he

print(f"{word[3:]}") output = lo!

print(f"{word[-1]}") output = !

print(f"{word[-2:]}") output = o!

If you are not sure how these work, open your IDE and try it out!

2. String Concatenation and Repetition

first_name = "Alice"
last_name = "Johnson"
full_name = first_name + " " + last_name  # Concatenation
print(full_name)
        
print("Hello! " * 3)  # Output: Hello! Hello! Hello!
        

3. String Formatting

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
        

3. String contents

word = "hello"
print("a" in word) output = false
        

4. Replacing content

word = "hello-jack"
newWord = word.replace("-", " ")
print(newWord) output "hello jack"
        

5. Practice Exercise

Write a program that:

  1. Asks for your name.
  2. Converts your name to uppercase.
  3. Puts a - between first and last name
  4. Prints a greeting using string formatting.
Enter your name: Alice Jones
HELLO, ALICE-JONES!
        

6. Real-World Coding Challenge

Create an email auto-correct tool:

  1. Ask the user to enter an email address.
  2. Convert it to lowercase.
  3. Remove any spaces.
  4. Check if the email contains "@" and "." in that order! If not, print: "Invalid email!".
  5. Otherwise, print: "Valid email entered: [email]".
Enter your email:  Example@Email.COM  
Valid email entered: example@email.com

Enter your email:  Example.Email@COM  
Invalid email!

Enter your email: wrongEmail.com
Invalid email!
        

Tags

datatype string uppercase lowercase length