🐍1.8Python string interview Comprehensive Guide to Strings in Python
Comprehensive Guide to Strings in Python
Strings are one of the most fundamental data types in Python. They are immutable sequences of characters used for storing and manipulating text. In this blog, we will explore various string operations, methods, and best practices.
1. Different Ways to Create a String in Python
Python provides multiple ways to create strings:
🔹 Single Quotes
s1 = 'Hello'
print(s1) # Output: Hello
🔹 Double Quotes
s2 = "World"
print(s2) # Output: World
🔹 Triple Quotes (for Multiline Strings)
s3 = '''This is a
multiline string.'''
print(s3)
🔹 Using str() Function
Converts other data types (e.g., integers) to strings.
s4 = str(123)
print(s4) # Output: '123'
2. Accessing Individual Characters in a String
Strings in Python are indexed, allowing access via positive or negative indexing.
s = "Python"
# Positive Indexing (0-based)
print(s[0]) # Output: P
print(s[3]) # Output: h
# Negative Indexing (from end)
print(s[-1]) # Output: n
print(s[-3]) # Output: h
3. Difference Between find() and index() Methods
| Method | Returns | When Substring Not Found | Case-Sensitive? |
|---|---|---|---|
find() |
First occurrence index | Returns -1 |
Yes |
index() |
First occurrence index | Raises ValueError |
Yes |
Example:
s = "Hello World"
print(s.find("World")) # Output: 6
print(s.find("Python")) # Output: -1 (Not found)
print(s.index("World")) # Output: 6
# print(s.index("Python")) # Raises ValueError
4. Reversing a String in Python
Using Slicing:
s = "Python"
print(s[::-1]) # Output: nohtyP
Using reversed():
print("".join(reversed(s))) # Output: nohtyP
Using a Loop:
rev = ""
for char in s:
rev = char + rev
print(rev) # Output: nohtyP
5. Checking if a String is a Palindrome
A palindrome is a string that reads the same forward and backward.
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam")) # True
print(is_palindrome("hello")) # False
6. Why Are Strings Immutable in Python?
Strings cannot be changed after creation due to:
- Performance: Reduces memory overhead.
- Security: Helps in handling sensitive data.
- Hashing: Strings can be used as dictionary keys.
Example:
s = "Python"
s[0] = "J" # Raises TypeError
To modify a string, create a new one:
s = "J" + s[1:]
print(s) # Output: Jython
7. Different String Formatting Techniques
1. Using + Operator (Concatenation)
name = "Alice"
age = 25
print("My name is " + name + " and I am " + str(age) + " years old.")
2. Using % Operator (Old Style)
print("My name is %s and I am %d years old." % (name, age))
3. Using .format() Method
print("My name is {} and I am {} years old.".format(name, age))
4. Using f-strings (Best & Modern)
print(f"My name is {name} and I am {age} years old.")
8. Removing Extra Spaces from a String
s = " Hello World "
print(s.strip()) # Output: "Hello World"
print(s.lstrip()) # Output: "Hello World "
print(s.rstrip()) # Output: " Hello World"
To remove extra spaces between words:
s = "Hello World"
print(" ".join(s.split())) # Output: "Hello World"
9. Checking if a String Contains Only Numeric Characters
Use .isdigit() method:
s1 = "12345"
s2 = "123abc"
print(s1.isdigit()) # Output: True
print(s2.isdigit()) # Output: False
For floating-point numbers:
s = "123.45"
print(s.replace(".", "").isdigit()) # Output: True
For alphanumeric check:
s = "Hello123"
print(s.isalnum()) # Output: True
10. Counting Occurrences of a Character in a String
Using .count():
s = "banana"
print(s.count("a")) # Output: 3
Using a loop:
count = 0
for char in s:
if char == "a":
count += 1
print(count) # Output: 3
Using collections.Counter:
from collections import Counter
char_count = Counter(s)
print(char_count["a"]) # Output: 3
Conclusion
Strings in Python are powerful and versatile. Understanding these fundamental operations will help you manipulate and work efficiently with textual data in Python.
Let me know if you need further explanations! 🚀
Comments
Post a Comment