Strings in Python - Interview Questions and Answers
A string is a sequence of characters enclosed in single, double, or triple quotes ('
, "
, '''
)
string1 = 'Hello'
string2 = "World"
string3 = '''Multiline
String'''
By indexing:
string = "Python"
print(string[0]) # P
print(string[-1]) # n
Using the len()
function
string = "Hello"
print(len(string)) # 5
Extracting a substring using start:end:step
string = "Python"
print(string[1:4]) # yth
print(string[:3]) # Pyt
print(string[::2]) # Pto
No, strings are immutable in Python, meaning their content cannot be changed after creation.
Functionally, there?s no difference. Double quotes are often used when the string contains a single quote:
string = "It's a string"
Using +
:
print("Hello" + " " + "World") # Hello World
Using *
print("Python " * 3) # Python Python Python
Using str()
num = 123
print(str(num)) # '123'
Using the in
keyword:
print("Py" in "Python") # True
Use lower()
and upper()
string = "Python"
print(string.lower()) # python
print(string.upper()) # PYTHON
Use strip()
string = " Hello "
print(string.strip()) # 'Hello'
find()
returns -1
if the substring is not found, while index()
raises a ValueError
.
Using replace()
:
string = "Hello World"
print(string.replace("World", "Python")) # Hello Python
Using split()
string = "a,b,c"
print(string.split(",")) # ['a', 'b', 'c']
Using join()
:
list_strings = ["a", "b", "c"]
print(",".join(list_strings)) # a,b,c
Inserting variables into strings using f-strings
or .format()
name = "Alice"
print(f"Hello, {name}!") # Hello, Alice!
Checks if a string is alphanumeric (contains only letters and numbers).
isalpha()
: Checks if all characters are alphabetic.isdigit()
: Checks if all characters are digits.
Using slicing:
string = "Python"
print(string[::-1]) # nohtyP
Strings prefixed with r
to prevent escape sequences:
raw_string = r"C:\new_folder"
print(raw_string) # C:\new_folder
Pads a string with zeros to the left:
print("42".zfill(5)) # 00042
Using startswith()
and endswith()
print("Python".startswith("Py")) # True
print("Python".endswith("on")) # True
Using count()
:
print("banana".count("a")) # 3
Using format()
or f-strings
print(f"{1000000:,}") # 1,000,000
capitalize()
: Capitalizes the first character of the string.title()
: Capitalizes the first character of each word.
Unicode is a standard for encoding text in multiple languages. Python strings support Unicode by default.
Using encode()
and decode()
encoded = "Hello".encode("utf-8")
decoded = encoded.decode("utf-8")
By reversing and comparing
string = "madam"
print(string == string[::-1]) # True
Formats a string using a dictionary:
data = {"name": "Alice", "age": 30}
print("{name} is {age}".format_map(data)) # Alice is 30
split()
splits from the left, rsplit()
splits from the right.
Using ord()
print(ord("A")) # 65
Using chr()
print(chr(65)) # A
Replaces characters based on a translation table:
table = str.maketrans("aeiou", "12345")
print("apple".translate(table)) # 1ppl2
Using replace()
or translate()
:
print("hello!".replace("!", "")) # hello
Splits a string into three parts: before, separator, and after
print("Hello,World".partition(",")) # ('Hello', ',', 'World')
Using sorted()
print("dcba".join(sorted("dcba"))) # abcd
Using isspace()
Expands tab characters to spaces:
print("Hello\tWorld".expandtabs(4))
join()
is faster and more efficient for combining multiple strings, especially when dealing with lists. Concatenation (+
) is simpler for combining two or three strings.
# Using join
words = ["Python", "is", "fun"]
print(" ".join(words)) # Python is fun
# Using concatenation
print("Python" + " is " + "fun") # Python is fun
Use a set()
to extract unique characters:
string = "programming"
unique_chars = set(string)
print(unique_chars) # {'g', 'r', 'a', 'o', 'n', 'm', 'i', 'p'}
Strings in Python are immutable, meaning their content cannot be changed after creation. Any modification creates a new string.
string = "Python"
string[0] = "J" # This raises a TypeError
string = "Java" # Creates a new string
Escape sequences allow special characters (like newline \n
, tab \t
) to be included in strings.
print("Hello\nWorld") # Outputs:
# Hello
# World
Using set()
and join()
string = "programming"
result = "".join(set(string))
print(result) # The order may vary
Python does not copy the sliced string into a new memory location. It uses the original string, which improves performance.
Use the split()
method or nltk
library for advanced tokenization
string = "Python is fun"
tokens = string.split() # ['Python', 'is', 'fun']
String literals are strings explicitly defined in code, enclosed in quotes
string = "Hello" # This is a string literal
Using isupper()
:
print("PYTHON".isupper()) # True
print("Python".isupper()) # False
casefold()
is used for case-insensitive comparisons. It converts strings to lowercase, considering language-specific cases.
print("?".casefold()) # 'ss'
Use f-strings
, format()
, or %
formatting
name = "Alice"
print(f"Hello, {name}") # Hello, Alice
strip()
: Removes leading and trailing spaces.lstrip()
: Removes leading spaces.rstrip()
: Removes trailing spaces.
string = " Hello "
print(string.strip()) # 'Hello'
print(string.lstrip()) # 'Hello '
print(string.rstrip()) # ' Hello'
Using isnumeric()
:
print("123".isnumeric()) # True
print("123a".isnumeric()) # False
isdecimal()
checks for decimal characters (0-9).isdigit()
includes decimal characters, superscripts, etc.
print("123".isdecimal()) # True
print("?".isdigit()) # True
Strings enclosed in triple quotes ('''
or """
) can span multiple lines
string = '''This is
a multiline
string.'''
Use a combination of split()
, find()
, or regular expressions:
import re
email = "test@example.com"
print(bool(re.match(r"[^@]+@[^@]+\.[^@]+", email))) # True
Use if not string
string = ""
print(not string) # True
These methods align strings to the left, right, or center
string = "Python"
print(string.ljust(10, "-")) # Python----
print(string.rjust(10, "-")) # ----Python
print(string.center(10, "-")) # --Python--
Strings in Python support Unicode by default. Use encode()
to convert to bytes and decode()
to convert back.
string = "caf?"
encoded = string.encode("utf-8")
print(encoded) # b'caf\xc3\xa9'
print(encoded.decode("utf-8")) # caf?
Using a loop or comprehension:
string = "Hello World"
vowels = "aeiouAEIOU"
count = sum(1 for char in string if char in vowels)
print(count) # 3
Tutorials
Random Blogs
- AI in Cybersecurity: The Future of Digital Protection
- Top 10 Knowledge for Machine Learning & Data Science Students
- Important Mistakes to Avoid While Advertising on Facebook
- The Ultimate Guide to Starting a Career in Computer Vision
- Internet of Things (IoT) & AI – Smart Devices and AI Working Together
- How to Become a Good Data Scientist ?
- Convert RBG Image to Gray Scale Image Using CV2
- String Operations in Python
- 5 Ways Use Jupyter Notebook Online Free of Cost
- How AI Companies Are Making Humans Fools and Exploiting Their Data