Python allows operators like +
and *
to behave differently depending on the type of data they are used with. For strings, these operators are used for:
(A) String Concatenation (+
Operator):
- The
+
operator joins (concatenates) two strings. - It creates a new string that is the combination of the two.
Syntax:
string1 + string2
Example:
name = "Alice"
greeting = "Hello, " + name
print(greeting)
Output: Hello, Alice
Note: You cannot concatenate a string with a number directly. You must first convert the number to a string using str()
.
age = 20
print("Age: " + str(age)) # Correct
(B) String Replication (*
Operator):
- The
*
operator repeats a string multiple times. - It requires one operand to be a string and the other to be an integer.
Syntax: string * number
Example:
pattern = "Ha"
laugh = pattern * 3
print(laugh)
Output: HaHaHa
Operator | Operation | Description |
---|---|---|
+ | Concatenation | Joins two strings |
* | Replication | Repeats a string multiple times |
