🐍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?

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:

  1. Immutable – Once created, they cannot be modified.
  2. Indexed & Slicable – Strings support indexing (s[0]) and slicing (s[1:4]).
  3. Dynamic Typing – No need to declare the type explicitly.
  4. 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:

OperationExampleOutput
Concatenation"Hello" + " World""Hello World"
Repetition"Hi" * 3"HiHiHi"
Lengthlen("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:

  1. Multi-line Strings:
    s = '''This is
    a multi-line
    string.'''
    
  2. Raw Strings (ignores escape characters):
    r = r"C:\Users\Documents\file.txt"
    

String Formatting Methods:

  1. Using format()
    name = "John"
    age = 25
    print("My name is {} and I am {} years old.".format(name, age))
    
  2. Using f-strings (Python 3.6+ recommended)
    print(f"My name is {name} and I am {age} years old.")
    
  3. 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

Popular posts from this blog

🌐Filtering and Copying Files Dynamically in Azure Data Factory (ADF)

🔥Apache Spark Architecture with RDD & DAG

🖥️☁️AWS Athena, AWS Lambda, AWS Glue, and Amazon S3 – Detailed Explanation