String Methods in Python

 

What are String Methods? 

String methods are built-in functions that help us manipulate and transform text easily. Think of them as a Swiss Army knife  for handling strings!

Why Use String Methods?

  • Save time! 
  • Make text processing easier! 
  • Write cleaner and more efficient code!

Changing Case

Convert to Uppercase/Lowercase

text = "Hello, Python!"
print(text.upper())  # Outputs: HELLO, PYTHON!
print(text.lower())  # Outputs: hello, python!

Capitalize First Letter

print(text.capitalize())  # Outputs: Hello, python!
print(text.title())  # Outputs: Hello, Python!

Removing Unwanted Spaces

text = "   Clean me up!   "
print(text.strip())  # Outputs: "Clean me up!"
print(text.lstrip())  # Removes leading spaces
print(text.rstrip())  # Removes trailing spaces

Finding & Replacing

Find a Word in a String

text = "Python is awesome!"
print(text.find("Python"))  # Outputs: 0
print(text.find("Java"))  # Outputs: -1 (not found)

Replace Text

print(text.replace("awesome", "fantastic"))  # Outputs: Python is fantastic!

Checking String Content

text = "12345"
print(text.isdigit())  # Outputs: True
print("hello".isalpha())  # Outputs: True (only letters)
print("Hello123".isalnum())  # Outputs: True (letters + numbers)
print("   ".isspace())  # Outputs: True (only spaces)

Splitting & Joining Strings

Split a String into a List

text = "apple,banana,grape"
fruits = text.split(",")
print(fruits)  # Outputs: ['apple', 'banana', 'grape']

Join a List into a String

new_text = "-".join(fruits)
print(new_text)  # Outputs: apple-banana-grape

Summary

Method Description
.upper() / .lower() Convert case
.strip() Remove whitespace
.find() Find position of a substring
.replace() Replace text in a string
.isdigit() / .isalpha() Check content type
.split() / .join() Break and merge strings

Post a Comment

0 Comments