Skip to content

Latest commit

 

History

History
141 lines (105 loc) · 3.84 KB

File metadata and controls

141 lines (105 loc) · 3.84 KB

Modifying and Splitting Strings

Python has a set of powerful built-in methods that you can use on strings to format, modify, and split them without needing to use complex loops or external libraries.


1. Changing Case (Upper and Lower)

You can instantly change the entire casing of a string using .upper() and .lower().

Input:

a = "Hello, World!"
print("Original:", a)

print("Uppercase:", a.upper())
print("Lowercase:", a.lower())

Output:

Original: Hello, World!
Uppercase: HELLO, WORLD!
Lowercase: hello, world!

2. Removing Whitespace (Trimming)

Whitespace is the space before and/or after the actual text. When taking input from users, they often accidentally type extra spaces.

Python gives us three methods to clean this up:

  • .strip(): Removes whitespace from both ends.
  • .lstrip(): Removes whitespace from the left side only.
  • .rstrip(): Removes whitespace from the right side only.
a = "   Hello, World!   "

print("'" + a.strip() + "'")  # 'Hello, World!'
print("'" + a.lstrip() + "'") # 'Hello, World!   '
print("'" + a.rstrip() + "'") # '   Hello, World!'

3. Replacing Text

The .replace() method replaces a string with another string. This is incredibly useful for cleaning up data!

Input:

a = "Hello, World!"

# Replace 'H' with 'J'
print(a.replace("H", "J"))

# Replace 'World' with 'Universe'
print(a.replace("World", "Universe"))

Output:

Jello, World!
Hello, Universe!

4. Splitting Strings into Lists

The .split() method splits a single string into a List of strings based on a specified separator (like a comma, or a space).

This is the absolute most common way to process comma-separated values (CSV) data in Python!

Input:

# Splitting by a comma
a = "apple, banana, cherry"
fruits_list = a.split(",")

print(fruits_list)
print("The first fruit is:", fruits_list[0])

# Splitting by a space (the default behavior)
sentence = "Python is a great language"
words_list = sentence.split(" ")

print(words_list)

Output:

['apple', ' banana', ' cherry']
The first fruit is: apple
['Python', 'is', 'a', 'great', 'language']

5. Searching and Finding

If you need to search a string for a specific word or character, Python provides several powerful methods.

count()

Returns the number of times a specified value appears in the string.

txt = "I love apples, apples are my favorite."
print(txt.count("apple")) # 2

find(), index(), rfind(), and rindex()

These methods search the string for a specified value and return the index position.

  • find(): Searches from left-to-right. Returns -1 if not found.
  • index(): Searches from left-to-right. Crashes with an error if not found.
  • rfind(): Searches from right-to-left (reverse). Returns -1 if not found.
  • rindex(): Searches from right-to-left. Crashes with an error if not found.
txt = "Hello, welcome to my world."

print(txt.find("o"))    # 4
print(txt.rfind("o"))   # 24
print(txt.find("z"))    # -1 (Safe, not found)
# print(txt.index("z")) # CRASHES THE SCRIPT

startswith() and endswith()

Instead of searching the whole string, these methods specifically check if the string begins or ends with a specific sequence. They return True or False.

txt = "Hello, welcome to my world."

print(txt.startswith("Hello")) # True
print(txt.endswith("."))       # True
print(txt.endswith("world"))   # False (ends with a period)