📝 Data Types & Strings
Complete solutions with detailed explanations
📋 Questions & Solutions
# Create a float and an integer
float_num = 3.14
int_num = 5
# Add them together
result = float_num + int_num
print("Sum (float):", result)
# Convert to integer and print
result_int = int(result)
print("Sum (integer):", result_int)Sum (float): 8.14 Sum (integer): 8
🎓 Explanation
int() truncates the decimal part (doesn't round). 8.14 becomes 8, not 8.14 rounded to 8.
text = "i live in india since my childhood"
# Count lowercase 'i'
count = text.count('i')
print("Number of 'i':", count)Number of 'i': 6
🎓 Explanation
.count() is case-sensitive. It counts: "i" (1st word), "i" in live, "i" in in, "i" and "i" in india, "i" in since, "i" in childhood = 6 total.
# Method 1: type() function
x = 10
print("Type of x:", type(x))
print("Is x an int?", type(x) == int)
# Method 2: isinstance() function (recommended)
y = "Hello"
print("Is y a string?", isinstance(y, str))
# isinstance can check multiple types
z = 3.14
print("Is z int or float?", isinstance(z, (int, float)))Type of x: <class 'int'> Is x an int? True Is y a string? True Is z int or float? True
🎓 Explanation
type() returns the exact type. isinstance() is preferred because it also works with inheritance and can check multiple types at once.
text = "Machine Learning"
# Using negative slicing
last_4 = text[-4:]
print("Last 4 characters:", last_4)Last 4 characters: ning
🎓 Explanation
[-4:] means start from 4th character from end, go till end. Negative indexing: -1 is last char, -2 is second last, etc.
text = "Machine Learning. "
# Remove trailing whitespace
cleaned = text.rstrip()
print("Original:", repr(text))
print("Cleaned:", repr(cleaned))
# Alternative: strip() removes from both ends
text2 = " Hello World "
print("strip():", repr(text2.strip()))Original: 'Machine Learning. ' Cleaned: 'Machine Learning.' strip(): 'Hello World'
🎓 Explanation
rstrip() removes trailing (right) whitespace. lstrip() removes leading (left). strip() removes both ends. repr() shows the string with quotes to visualize spaces.
text = "Data Science with Python"
# Using slicing with step 2
every_second = text[::2]
print("Every second character:", every_second)
# Alternative: manual loop
result = ""
for i in range(0, len(text), 2):
result += text[i]
print("Loop method:", result)Every second character: Dt cec ihPto Loop method: Dt cec ihPto
🎓 Explanation
[::2] means start:end:step. Empty start/end = full string, step 2 = every 2nd char. Characters at index 0, 2, 4, 6... are selected.
# Convert to string first if it's an integer
value = 265
value_str = str(value)
# Check if all characters are digits
is_digit = value_str.isdigit()
print(f"'{value}' is digit: {is_digit}")
# Can also check individual characters
text = "Hello123"
for char in text:
print(f"'{char}' is digit: {char.isdigit()}")'265' is digit: True 'H' is digit: False 'e' is digit: False 'l' is digit: False 'l' is digit: False 'o' is digit: False '1' is digit: True '2' is digit: True '3' is digit: True
🎓 Explanation
.isdigit() returns True if all characters in the string are digits (0-9). It's a string method, so convert numbers to string first.
text = "MACHINE LEARNING"
# Convert to lowercase
lowercase = text.lower()
print("Lowercase:", lowercase)
# Also useful: upper(), title(), capitalize()
print("Upper:", text.upper())
print("Title:", text.title())
print("Capitalize:", text.capitalize())Lowercase: machine learning Upper: MACHINE LEARNING Title: Machine Learning Capitalize: Machine learning
🎓 Explanation
.lower() converts all to lowercase. .upper() to uppercase. .title() capitalizes each word. .capitalize() only first letter of string.
text = "Machine Learning and Deep Learning"
# Count occurrences of 'e'
count = text.count('e')
print(f"Number of 'e': {count}")
# Case-insensitive count (if needed)
count_all = text.lower().count('e')
print(f"Number of 'e' (case-insensitive): {count_all}")Number of 'e': 5 Number of 'e' (case-insensitive): 5
🎓 Explanation
.count('e') counts all lowercase 'e'. The 'e' appears in: Machine, Learning (x2), Deep, Learning (x2) = 5 times.
string1 = "HelloPython"
string2 = "Hello Python" # has space
string3 = "Hello123" # has numbers
print(f"'{string1}' is alphabetic: {string1.isalpha()}")
print(f"'{string2}' is alphabetic: {string2.isalpha()}")
print(f"'{string3}' is alphabetic: {string3.isalpha()}")'HelloPython' is alphabetic: True 'Hello Python' is alphabetic: False 'Hello123' is alphabetic: False
🎓 Explanation
.isalpha() returns True ONLY if ALL characters are letters (a-z, A-Z). Spaces, numbers, and special characters make it False.