Python:Python Strings: Slicing, Escaping, and Built-in Methods
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:

ParameterTypeDescription
str.split()MethodSplits string into a list of substrings.
str.join()MethodConcatenates elements of an iterable with delimiter.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler