Operation on Strings
In Python, strings support a variety of operations and methods for manipulation
1. Concatenation:
Combining two or more strings together.
str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2 # 'Hello, World'
2. Repetition:
Repeating a string multiple times.
original = "abc"
repeated = original * 3 # 'abcabcabc'
3. Slicing:
Extracting a portion of a string using indexing.
message = "Python is awesome"
substring = message[7:10] # 'is '
4. Length:
Finding the length of a string.
text = "Python"
length = len(text) # 6
5. String Methods:
Python provides various built-in string methods for manipulation, including:
upper()
: Converts all characters to uppercase.lower()
: Converts all characters to lowercase.replace(old, new)
: Replaces occurrences ofold
withnew
.find(substring)
: Returns the index of the first occurrence ofsubstring
(or -1 if not found).split(separator)
: Splits the string into a list of substrings using the specifiedseparator
.strip()
: Removes leading and trailing whitespaces.
phrase = "Python is easy to learn"
upper_case = phrase.upper() # 'PYTHON IS EASY TO LEARN'
lower_case = phrase.lower() # 'python is easy to learn'
replaced = phrase.replace("easy", "fun") # 'Python is fun to learn'
index_of_learn = phrase.find("learn") # 15
words = phrase.split() # ['Python', 'is', 'easy', 'to', 'learn']
stripped = " hello ".strip() # 'hello'
6. String Formatting:
Combining variables or expressions with a string.
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
7. Checking Substrings:
Checking if a substring is present in a string.
text = "Python is powerful"
contains_python = "Python" in text # True
8. Conversion:
Converting other data types to strings.
num = 42
str_num = str(num) # '42'
9. Escape Characters:
Using escape characters to include special characters in a string.
multiline_text = "This is a\nmultiline\nstring."
10. String Comparison:
Comparing strings lexicographically.
str1 = "apple"
str2 = "banana"
is_greater = str1 > str2 # False
Understanding these operations and methods allows you to manipulate and process strings effectively in Python. Strings are a fundamental part of programming and are used in various applications, from simple text processing to complex data handling.