Python strings

String concatenation and replication are operations that allow you to manipulate and work with strings in Python.

  • String Concatenation:
  • String concatenation is the process of combining two or more strings to create a single string. This is achieved using the "+" operator.

    Example:

    first_name = "John"
    last_name = "Doe"
    
    full_name = first_name + " " + last_name
    print(full_name)  # Output: "John Doe"

    In this example, the "+" operator is used to concatenate the first_name, a space, and the last_name to create the full_name string.

  • String Replication:
  • String replication involves creating a new string by repeating another string a certain number of times. This is done using the "*" operator.

    Example:

    message = "Hello!"
    
    repeated_message = message * 3
    print(repeated_message)  # Output: "Hello!Hello!Hello!"

    In this example, the "*" operator replicates the "message" string three times, creating the "repeated_message".

  • Combining Concatenation and Replication:
  • You can also use string concatenation and replication together to create more complex strings.

    Example:

    greeting = "Hi, " + full_name + "! "
    repeated_greeting = greeting * 2
    
    print(repeated_greeting)  # Output: "Hi, John Doe! Hi, John Doe! "

    Here, the "greeting" string is created by concatenating the "Hi, ", "full_name", and "! " strings. Then, the "*" operator is used to replicate the "greeting" string twice, resulting in the "repeated_greeting".

String concatenation and replication are powerful tools for creating dynamic strings, building messages, and formatting output in your Python programs.