🐍1.1String in Python - Interview Explanation detail
What is a String in Python?
A string in Python is an immutable sequence of characters enclosed within single ('
or "
), double ("
or "
), or triple quotes ('''
or """
). It is a fundamental data type used to represent text.
Characteristics of Python Strings:
- Immutable – Once created, they cannot be modified.
- Indexed & Slicable – Strings support indexing (
s[0]
) and slicing (s[1:4]
). - Dynamic Typing – No need to declare the type explicitly.
- Unicode Support – Python strings support Unicode characters.
- Strings are indexed, meaning you can access characters using their position (positive and negative indexing).
Slicing extracts parts of a string using string[start:end:step]
.
start
(default=0) → Inclusive (included in the result)end
(default=last index) → Exclusive (not included in the result)step
→ Optional, defines the jump
1. String Creation
# Single and Double Quotes
s1 = 'Hello'
s2 = "World"
# Triple Quotes for Multiline String
s3 = '''This is
a multiline
string.'''
2. Accessing String Elements
s = "Python"
print(s[0]) # Output: P (Positive Indexing)
print(s[-1]) # Output: n (Negative Indexing)
3. String Slicing
s = "Python"
print(s[0:4]) # Output: Pyth (from index 0 to 3)
print(s[:4]) # Output: Pyth (default start=0)
print(s[2:]) # Output: thon (default end=last index)
print(s[::2]) # Output: Pto (every 2nd character)
4. String Methods
Case Conversion
s = "hello world"
print(s.upper()) # HELLO WORLD
print(s.lower()) # hello world
print(s.title()) # Hello World
print(s.capitalize()) # Hello world
print(s.swapcase()) # HELLO WORLD
Checking & Searching
s = "Hello Python"
print(s.startswith("Hello")) # True
print(s.endswith("Python")) # True
print(s.find("Py")) # 6 (index of first occurrence)
print(s.count("o")) # 2 (count of 'o')
Modification
s = " Python "
print(s.strip()) # "Python" (removes spaces from both sides)
print(s.lstrip()) # "Python " (removes left spaces)
print(s.rstrip()) # " Python" (removes right spaces)
Replacing & Splitting
s = "Hello, World"
print(s.replace("World", "Python")) # Hello, Python
s = "Python is fun"
print(s.split()) # ['Python', 'is', 'fun'] (default split on space)
s = "one,two,three"
print(s.split(",")) # ['one', 'two', 'three']
Python split()
Method Table
Method | Description |
---|---|
string.split() |
Splits by spaces (default). |
string.split(",") |
Splits using a comma. |
string.split("\n") |
Splits by newlines. |
string.split(" ", 2) |
Splits only twice. |
re.split(r"[;, ]", s) |
Splits using multiple delimiters. |
5. String Concatenation and Repetition
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # Hello World (Concatenation)
print(s1 * 3) # HelloHelloHello (Repetition)
6. String Formatting
Using f-strings (Python 3.6+)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Using .format()
Method
print("My name is {} and I am {} years old.".format(name, age))
Using %
Operator
print("My name is %s and I am %d years old." % (name, age))
7. String Encoding & Decoding
s = "Hello"
encoded_s = s.encode("utf-8") # Encoding to bytes
print(encoded_s) # b'Hello'
decoded_s = encoded_s.decode("utf-8") # Decoding back to string
print(decoded_s) # Hello
8. String Immutability
s = "Python"
s[0] = "J" # Raises an error (strings are immutable)
To modify, create a new string:
s = "J" + s[1:]
print(s) # Jython
9. Reversing a String
s = "Python"
print(s[::-1]) # nohtyP
10. Checking If a String is a Palindrome
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam")) # True
print(is_palindrome("hello")) # False
Comments
Post a Comment