🐍1.14What is a String in Python?
If you're preparing for an interview, here's a structured and professional answer about Python Strings:
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.
Example:
s = "Hello, World!"
print(s[0]) # Output: H
print(s[-1]) # Output: !
print(s[0:5]) # Output: Hello
Common String Operations:
Operation | Example | Output |
---|---|---|
Concatenation | "Hello" + " World" | "Hello World" |
Repetition | "Hi" * 3 | "HiHiHi" |
Length | len("Python") | 6 |
Uppercase | "python".upper() | "PYTHON" |
Lowercase | "PYTHON".lower() | "python" |
Strip spaces | " hello ".strip() | "hello" |
Replace substring | "Hello".replace("H", "J") | "Jello" |
Split string | "a,b,c".split(",") | ['a', 'b', 'c'] |
Special Types of Strings:
- Multi-line Strings:
s = '''This is a multi-line string.'''
- Raw Strings (ignores escape characters):
r = r"C:\Users\Documents\file.txt"
String Formatting Methods:
- Using
format()
name = "John" age = 25 print("My name is {} and I am {} years old.".format(name, age))
- Using f-strings (Python 3.6+ recommended)
print(f"My name is {name} and I am {age} years old.")
- Using
%
formatting (Old method, not recommended)print("My name is %s and I am %d years old." % (name, age))
Key Points to Remember for Interviews:
- Strings are immutable in Python.
- They support indexing, slicing, and various built-in methods.
- Use f-strings for efficient string formatting.
- Python supports Unicode by default.
- Use
split()
,replace()
,strip()
for text processing.
Would you like practice questions related to Python strings? 🚀
Comments
Post a Comment