Basic Python String Operations | Generated by AI

Home 2025.12

Question: What are the basic operations on strings in Python?

Answer:

Strings in Python are immutable sequences of characters. They support a variety of built-in operations and methods for manipulation.

Common Basic Operations

Common String Methods

Examples

s = "Hello, World!"

# Length
len(s)                    # 13

# Indexing and slicing
s[0]                      # 'H'
s[-1]                     # '!'
s[0:5]                    # 'Hello'
s[7:]                     # 'World!'
s[:-7]                    # 'Hello,'

# Case conversion
s.upper()                 # 'HELLO, WORLD!'
s.lower()                 # 'hello, world!'

# Replace
s.replace("World", "Python")  # 'Hello, Python!'

# Split and join
s.split(",")              # ['Hello', ' World!']
" ".join(["Hello", "Grok"])  # 'Hello Grok'

# Strip
"  spaced  ".strip()      # 'spaced'

# Find
s.find("World")           # 7
s.find("xyz")             # -1

# Starts/ends with
s.startswith("Hello")     # True
s.endswith("!")           # True

# Concatenation and repetition
s + " Again."             # 'Hello, World! Again.'
"Hi" * 3                  # 'HiHiHi'

# f-string
name = "Alice"
age = 30
f"{name} is {age} years old."  # 'Alice is 30 years old.'

These operations do not modify the original string (since strings are immutable); they return new strings instead.


Back

x-ai/grok-4.1-fast

Donate