0
0
Pythonprogramming~5 mins

Common string transformations in Python

Choose your learning style9 modes available
Introduction

Strings are words or sentences in code. Changing them helps us clean, format, or prepare text for different uses.

When you want to make all letters uppercase or lowercase for easy comparison.
When you need to remove extra spaces from user input.
When you want to replace certain words or characters in a sentence.
When you want to split a sentence into words or join words into a sentence.
When you want to check if a string starts or ends with a certain word.
Syntax
Python
string.upper()
string.lower()
string.strip()
string.replace(old, new)
string.split(separator)
separator.join(list_of_strings)
string.startswith(prefix)
string.endswith(suffix)

These methods do not change the original string but return a new one.

Strings are like beads on a string; these methods help rearrange or clean them.

Examples
Makes all letters uppercase: HELLO WORLD
Python
text = "Hello World"
print(text.upper())
Removes spaces at the start and end: 'hello'
Python
text = "  hello  "
print(text.strip())
Splits the string into a list of fruits
Python
text = "apple,banana,orange"
fruits = text.split(",")
print(fruits)
Joins words into a sentence with spaces
Python
words = ["I", "love", "Python"]
sentence = " ".join(words)
print(sentence)
Sample Program

This program shows many common string changes: uppercase, trimming spaces, replacing characters, splitting, joining, and checking start/end.

Python
text = "  Hello, Python World!  "

# Make uppercase
upper_text = text.upper()

# Remove spaces
clean_text = text.strip()

# Replace comma with dash
replaced_text = clean_text.replace(",", " -")

# Split into words
words = replaced_text.split()

# Join words with underscore
joined_text = "_".join(words)

# Check start and end
starts_with_hello = clean_text.startswith("Hello")
ends_with_world = clean_text.endswith("World!")

print("Uppercase:", upper_text)
print("Cleaned:", clean_text)
print("Replaced:", replaced_text)
print("Words:", words)
print("Joined:", joined_text)
print("Starts with 'Hello':", starts_with_hello)
print("Ends with 'World!':", ends_with_world)
OutputSuccess
Important Notes

Remember strings are not changed directly; methods return new strings.

Use strip() to clean user input before processing.

split() without arguments splits on any whitespace.

Summary

Use string methods to change or check text easily.

Common methods: upper(), lower(), strip(), replace(), split(), join(), startswith(), endswith().

These help prepare text for display, comparison, or storage.