Python•Strings
Python Strings: Slicing, Escaping, and Built-in Methods
Learn how to manipulate text using split(), join(), strip(), replace(), f-strings, and string slicing techniques.
Syntax
text = "Sample String"
formatted = f"Hello {text}"
words = text.split(",")
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| str.split() | Method | Splits string into a list of substrings. |
| str.join() | Method | Concatenates elements of an iterable with delimiter. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Python locally:
# String Formatting and Common Methods
raw_input = " [email protected], [email protected] "
# Clean whitespace and split by delimiter
cleaned = raw_input.strip()
emails = [e.strip() for e in cleaned.split(",")]
print(f"Parsed Emails: {emails}")
# String search & replacement
domain_target = "compilra.dev"
for email in emails:
if email.endswith(domain_target):
prefix = email.split("@")[0]
print(f"Verified internal user: {prefix.upper()}")
# Joining elements
joined_names = " | ".join(["Python", "JavaScript", "C++"])
print(f"Joined: {joined_names}")Expected Output:
Parsed Emails: ['[email protected]', '[email protected]'] Verified internal user: ADMIN Verified internal user: DEVELOPER Joined: Python | JavaScript | C++
How It Works: Step-by-Step
- Lines 5-6: strip() cleans surrounding whitespace; split(",") separates tokens.
- Lines 11-14: endswith() verifies suffix, and .upper() transforms casing.
- Line 17: join() combines list elements with custom delimiter string.
Key Concepts
- Strings in Python are immutable; methods return new strings rather than mutating.
- str.strip() removes leading and trailing whitespace characters.
- str.split(sep) partitions strings into list items based on delimiter.
Common Mistake: Assuming string methods modify the string in place
Since strings are immutable, methods return a new string. You must reassign the result.
❌ Incorrect
name = " alex " name.strip() # Does NOT change name
✅ Correct
name = " alex " name = name.strip() # Correctly reassigns "alex"
Related Python Tutorials & Compiler
Python Lists: Operations, Slicing, and Built-in Methods
Lists are ordered, mutable collections of items. They are one of the most versatile built-in data types in Python.
Python Input and Output (I/O) with print() and input()
Learn how to display outputs to the console using print() and receive interactive user input with input().
Python Variables and Data Types with Examples
Variables in Python are containers for storing data values. Python is dynamically typed, so you do not need to declare types explicitly.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.