Back to Blog

Python Tutorial for Beginners #3 - String Operations (Methods, Slicing, f-strings)

Sandy LaneSandy Lane

Video: Python Tutorial for Beginners #3 - String Operations (Methods, Slicing, f-strings) by Taught by Celeste AI - AI Coding Coach

Watch full page →

Python String Operations: Methods, Slicing, and f-strings

Strings are a fundamental data type in Python, used to store and manipulate text. This guide covers creating strings with quotes, combining them, formatting with f-strings, using common string methods, and accessing parts of strings through indexing and slicing.

Code

# String basics: creating and combining strings
greeting = "Hello"
name = 'World'
message = greeting + ", " + name + "!"  # Concatenation
print(message)  # Output: Hello, World!

# f-strings: embed variables directly in strings
age = 25
print(f"I am {age} years old")  # Output: I am 25 years old

# Common string methods
text = "  Python Programming  "
print(text.strip())   # Removes leading/trailing whitespace: "Python Programming"
print(text.upper())   # Converts to uppercase: "  PYTHON PROGRAMMING  "

words = "a,b,c".split(",")  # Splits into list: ['a', 'b', 'c']
rejoined = "-".join(words)   # Joins list into string: "a-b-c"
print(rejoined)

# Indexing and slicing strings
word = "Python"
print(word[0])      # First character: 'P'
print(word[-1])     # Last character: 'n'
print(word[0:3])    # Slice from index 0 up to (not including) 3: 'Pyt'
print(word[::-1])   # Reverses the string: 'nohtyP'

Key Points

  • Strings can be created with single or double quotes and combined using the + operator.
  • f-strings allow embedding variables or expressions inside strings using curly braces.
  • Common string methods include strip() to trim whitespace, upper()/lower() to change case, split() to break into lists, and join() to combine lists into strings.
  • Strings support indexing to access individual characters and slicing to extract substrings using start:end syntax.
  • Negative indices count from the end, and a step of -1 in slicing reverses the string.