Built with Tutify.io

    AIStudyLabs

    Strings: Basics and Common Operations

    Strings: Basics and Common Operations

    Introduction

    In this lesson, you will work with one of the most important data types in Python: strings. You already know how to print and format basic text; now we’ll dig deeper into how strings are created, indexed, sliced, combined, transformed, and safely converted to and from other data types.

    By the end of this lesson, you’ll be comfortable accessing specific characters and substrings, using common string methods, formatting output clearly, and handling conversions between strings and numbers.


    1. What Is a String in Python?

    A string is an ordered sequence of characters enclosed in quotes. Strings are immutable, meaning you cannot change them in place, only create new ones.

    1.1 Single Quotes vs Double Quotes

    Python allows both single (') and double (") quotes to define strings. They behave the same; you choose based on convenience or style.

    single_quoted = 'Hello, Python'
    double_quoted = "Hello, Python"
    
    print(single_quoted)
    print(double_quoted)
    
    # Output:
    Hello, Python
    Hello, Python
    

    You typically pick the quote style that makes it easier to include the other type inside the string without escaping:

    message1 = "I'm learning Python"       # contains a single quote
    message2 = 'He said "Python is fun"'  # contains double quotes
    
    print(message1)
    print(message2)
    
    # Output:
    I'm learning Python
    He said "Python is fun"
    

    1.2 Multi-line Strings

    Use triple quotes for multi-line strings, often for long text or documentation:

    description = """This is a multi-line string.
    It can span multiple lines
    without using \n manually."""
    
    print(description)
    
    # Output:
    This is a multi-line string.
    It can span multiple lines
    without using \n manually.
    

    Triple quotes work with either ''' or """.


    2. Accessing Characters and Substrings

    Strings are sequences, so you can access characters by index and extract slices.

    2.1 Positive and Negative Indexing

    Indexes start at 0 from the left and -1 from the right.

    text = "Python"
    
    first_char = text[0]     # 'P'
    third_char = text[2]     # 't'
    last_char = text[-1]     # 'n'
    second_last = text[-2]   # 'o'
    
    print(first_char, third_char, last_char, second_last)
    
    # Output:
    P t n o
    

    Trying to access an index outside the range will raise an IndexError, so indexing is best when you know the string length or have validated it.

    2.2 Slicing Strings

    Slicing uses string[start:end:step] to get a substring:

    text = "Programming"
    
    first_four = text[0:4]     # 'Prog'
    from_four_on = text[4:]    # 'ramming'
    up_to_four = text[:4]      # 'Prog'
    
    last_three = text[-3:]     # 'ing'
    
    skip_one = text[0:10:2]    # 'Pormn'
    reversed_text = text[::-1] # 'gnimmargorP'
    
    print(first_four)
    print(from_four_on)
    print(up_to_four)
    print(last_three)
    print(skip_one)
    print(reversed_text)
    
    # Output:
    Prog
    ramming
    Prog
    ing
    Pormn
    gnimmargorP
    

    Use slicing when you need parts of a string, such as extracting a file extension or a domain name from a URL.


    3. Combining, Repeating, and Formatting Strings

    3.1 Concatenation (Combining Strings)

    Use + to join strings and += to append to an existing string variable (creates a new string under the hood):

    first_name = "Ada"
    last_name = "Lovelace"
    
    full_name = first_name + " " + last_name
    
    print(full_name)
    
    # Output:
    Ada Lovelace
    

    For joining many pieces, str.join() (seen later) is often better than repeated + for performance and clarity.

    3.2 Repetition

    Use * to repeat a string:

    separator = "-" * 20
    line = "Python" * 3
    
    print(separator)
    print(line)
    
    # Output:
    --------------------
    PythonPythonPython
    

    3.3 f-Strings for Readable Formatting

    You already used basic f-strings; here’s a slightly richer example for combining text and expressions:

    name = "Maria"
    completed_tasks = 7
    total_tasks = 10
    
    progress = completed_tasks / total_tasks
    
    message = f"User {name} completed {completed_tasks}/{total_tasks} tasks ({progress:.0%} done)."
    
    print(message)
    
    # Output:
    User Maria completed 7/10 tasks (70% done).
    

    {progress:.0%} formats the fraction as a percentage with zero decimal places.


    4. Common String Methods

    String methods return new strings; the original remains unchanged.

    4.1 Changing Case

    text = "  Python Strings  "
    
    print(text.lower())   # all lowercase
    print(text.upper())   # all uppercase
    print(text.title())   # Capitalizes Each Word
    print(text.capitalize())  # First word capitalized only
    
    # Output:
      python strings  
      PYTHON STRINGS  
      Python Strings  
      python strings  
    

    4.2 Trimming Whitespace

    Use strip() and its variants to remove extra space from the start and/or end.

    raw_input_value = "   hello world  \n"
    
    clean_both = raw_input_value.strip()
    clean_left = raw_input_value.lstrip()
    clean_right = raw_input_value.rstrip()
    
    print(repr(clean_both))
    print(repr(clean_left))
    print(repr(clean_right))
    
    # Output:
    'hello world'
    'hello world  \n'
    '   hello world'
    

    repr() shows the hidden characters like \n and spaces.

    4.3 Searching and Checking Content

    text = "learn python programming"
    
    contains_python = "python" in text          # True
    position = text.find("python")              # 6 (index) or -1 if not found
    starts = text.startswith("learn")           # True
    ends = text.endswith("programming")         # True
    
    print(contains_python)
    print(position)
    print(starts)
    print(ends)
    
    # Output:
    True
    6
    True
    True
    

    Use in for quick membership tests, and find() when you need the index.

    4.4 Replacing Substrings

    template = "I like Java. Java is powerful."
    
    updated = template.replace("Java", "Python")
    
    print(updated)
    
    # Output:
    I like Python. Python is powerful.
    

    You can pass a third argument to limit replacements, e.g. replace("Java", "Python", 1).

    4.5 Splitting and Joining Strings

    Split a string into a list using a delimiter, then join it back with another delimiter.

    csv_line = "apple,banana,orange"
    
    fruits = csv_line.split(",")      # ['apple', 'banana', 'orange']
    joined = " | ".join(fruits)        # 'apple | banana | orange'
    
    print(fruits)
    print(joined)
    
    # Output:
    ['apple', 'banana', 'orange']
    apple | banana | orange
    

    This is common when processing user input, files, or simple data formats.


    5. Safe Type Conversion With Strings

    You often need to convert between strings and numbers, especially when working with input().

    5.1 Converting Other Types to String

    Use str() to convert numbers or other objects to strings for display or concatenation.

    age = 28
    temperature = 21.5
    
    info = "Age: " + str(age) + ", Temperature: " + str(temperature)
    
    print(info)
    
    # Output:
    Age: 28, Temperature: 21.5
    

    5.2 Converting Strings to Numbers Safely

    Use int() or float() and validate the input before converting to avoid errors.

    user_input = "42"  # imagine this came from input()
    
    if user_input.isdigit():
        value = int(user_input)
        result = value * 2
        print(f"Converted value: {value}, doubled: {result}")
    else:
        print("Please enter a valid whole number.")
    
    # Output:
    Converted value: 42, doubled: 84
    

    For decimal numbers, you can use a slightly more flexible check or handle errors with try/except (you’ll learn more about error handling later):

    data = "3.14"
    
    try:
        numeric_value = float(data)
        print(f"Successfully converted to float: {numeric_value}")
    except ValueError:
        print("Invalid number format.")
    
    # Output:
    Successfully converted to float: 3.14
    

    Summary / Key Takeaways

    In this lesson on Strings: Basics and Common Operations, you have learned:

    Python Programming – Complete Course with Practical Examples — Variables, Data Types, and Type Conversion

    Getting Started with Python and the Course

    Python Syntax, Indentation, and Core Concepts

    Variables, Data Types, and Type Conversion

    Operators, Expressions, and Control Flow

    Loops and Iteration Patterns

    Working with Strings in Depth

    Collections: Lists, Tuples, Sets, and Dictionaries

    Functions and Program Structuring

    Functional Programming Concepts in Python

    Modules, Packages, and Code Organization

    Error Handling and Debugging Fundamentals

    File Handling and Data Formats

    Object-Oriented Programming in Python

    Advanced Python: Iterators, Generators, and Decorators

    Python Standard Library for Real-World Tasks

    Python for Automation and Scripting

    Testing and Quality Assurance in Python

    Tutorial Not Found