String Operations in Python 3
In Python 3, strings support various operations that allow us to manipulate, combine, access, and analyze textual data. In this article, we will learn string operations one by one with clear explanations and examples.
1. String Concatenation (+)
Concatenation means joining two or more strings together. In Python, the + operator is used for this purpose.
a = "Hello"
b = "World"
result = a + " " + b
print(result)
2. String Repetition (*)
The repetition operation is used to repeat a string multiple times using the * operator.
text = "Python "
print(text * 3)
3. Indexing
Indexing allows us to access individual characters from a string. Index values start from 0.
word = "Python"
print(word[0]) # P
print(word[2]) # t
print(word[-1]) # n
4. Slicing
Slicing is used to extract a part of a string using a range of indexes.
The syntax is string[start : end].
text = "Programming"
print(text[0:6])
print(text[3:8])
print(text[:4])
print(text[5:])
Progra
gramm
Prog
mming
5. Membership Operation (in / not in)
Membership operators are used to check whether a substring exists inside a string.
msg = "python programming"
print("python" in msg)
print("java" not in msg)
Output: True
6. Comparison Operations
Strings can be compared using comparison operators. Comparison is done based on ASCII values.
print("apple" == "apple")
print("apple" > "banana")
print("Python" != "python")
7. Length Operation (len)
The len() function returns the number of characters in a string.
language = "Developer"
print(len(language))
8. String Immutability
Strings in Python are immutable. This means their characters cannot be changed directly.
s = "hello"
s[0] = "H" # Error
Conclusion
String operations are fundamental in Python programming. Understanding these operations helps in text processing, data validation, and real-world application development.
No comments:
Post a Comment