Operations with Strings
Python provides various operations that can be performed on strings, such as concatenation, repetition, membership testing, and more. In this lesson, we will explore these operations and how they can be used effectively.
String Concatenation (+
)
Concatenation is the process of joining two or more strings together using the +
operator.
Example:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
Here, the +
operator is used to join first_name
, a space " "
, and last_name
.
String Repetition (*
)
You can repeat a string multiple times using the *
operator.
Example:
word = "Hello "
print(word * 3) # Output: Hello Hello Hello
Membership Testing (in
and not in
)
You can check if a substring exists within a string using in
or not in
.
Example:
text = "Python is fun"
print("Python" in text) # Output: True
print("Java" not in text) # Output: True
Here, "Python" in text
returns True
because "Python"
exists in text
, while "Java" not in text
is also True
because "Java"
is not found.
Comparing Strings
Strings can be compared using comparison operators like ==
, !=
, <
, >
, <=
, and >=
.
Example:
print("apple" == "apple") # Output: True
print("apple" != "banana") # Output: True
print("apple" < "banana") # Output: True (lexicographic order)
Python compares strings based on their lexicographic order (dictionary order).
Escape Characters (\
)
Escape characters allow us to include special characters in strings.
Common escape characters:
\n
? New line\t
? Tab space\'
? Single quote\"
? Double quote\\
? Backslash
Example:
print("Hello\nWorld!") # Output:
# Hello
# World!
print("He said, \"Python is awesome!\"") # Output: He said, "Python is awesome!"
Exercise: Try It Yourself!
- Write a Python program that concatenates three strings and prints the result.
- Create a string and repeat it 5 times using the
*
operator. - Check if the word
"fun"
exists in the string"Learning Python is fun!"
. - Compare the strings
"apple"
and"orange"
using comparison operators.