The in and not in Membership Operators
These operators verify weather a substring or element exists within a sequence. in returns True when the target is found, while not in returns True when the target is absent.
username = "alexander"
if "alex" in username:
print('Substring located')
else:
print('Substring missing')
if "xan" not in username:
print('xan is absent')
else:
print('xan is present')
Boolean Values
The boolean type holds either True or False, which are essential for controlling program flow and evaluating logical conditions.
Fundamantal Data Types
Integer (int)
The int class provides numerous built-in capabilities.
# Convert a string to an integer, optionally specifying a base
numeric_str = "321"
converted = int(numeric_str)
print(type(converted), converted)
hex_str = "00FF"
value = int(hex_str, base=16)
print(value)
# Determine the minimum bits needed for binary representation
age_value = 42
bit_count = age_value.bit_length()
print(bit_count)
String (str)
String objects come with a rich set of methods for formatting, testing, and transforming text.
text = "pYthOn"
# Change case of the first character
capitalized = text.capitalize()
print(capitalized)
# Center align with padding
centered_text = text.center(30, "-")
print(centered_text)
# Count occurrences within a slice
sample = "abracadabra"
occurrences = sample.count('ab', 0, 10)
print(occurrences)
# Check beginning and ending substrings
print(text.endswith('on'))
print(text.startswith('pY'))
# Locate the index of a substring within a range
position = text.find('th', 1, 5)
print(position)
# Format strings using named or positional placeholders
template = 'Hello {user}, your score is {score}'
formatted = template.format(user='Eve', score=95)
print(formatted)
template2 = 'Coordinates: {0}, {1}'
formatted2 = template2.format(100, 200)
print(formatted2)
# Validate character composition
mixed = "test123"
print(mixed.isalnum()) # Alphanumeric check
alpha_only = "Hello"
print(alpha_only.isalpha())
digit_only = "9876"
print(digit_only.isdigit())
# Swap character cases
original = "PyThoN"
swapped = original.swapcase()
print(swapped)
# Convert to uppercase or lowercase
automaker = "Mercedes"
print(automaker.upper())
print(automaker.lower())
print(automaker.isupper())
print(automaker.islower())
# Validate title casing
book_title = "War And Peace"
print(book_title.istitle())
print(book_title.title())
# Join iterables with a separator
fragments = ["networking", "security", "cloud"]
joined = " - ".join(fragments)
print(joined)
# Pad or justify strings
label = "data"
left_padded = label.ljust(12, ".")
right_padded = label.rjust(12, ".")
zero_filled = label.zfill(10)
print(left_padded, right_padded, zero_filled)
# Strip whitespace or specific characters
entry = " ..important.. "
trimmed = entry.strip(" .")
print(trimmed)
# Split strings into parts
log_line = "ERROR:disk:full"
partition_result = log_line.partition(':')
print(partition_result)
multi_line = "line1\nline2\nline3"
split_lines = multi_line.splitlines(keepends=True)
print(split_lines)
# Replace substrings (optionally limiting replacements)
phrase = "foo bar foo baz foo"
modified_phrase = phrase.replace("foo", "qux", 2)
print(modified_phrase)
Key String Principles:
- Core operations: join, split, find, strip, upper, lower, replace.
- Iterative tools: for loops, len, slicing, indexing.
- Immutability: Strings cannot be altered in place; modifications create new string objects.
Exercises and Practical Scenarios
- Index enumeration: Accept user input and display each character with its index.
user_input = input("Enter text: ")
for idx in range(len(user_input)):
print(idx, user_input[idx])
- Integer addition calculator: Parse an expression like "12+ 7" and compute the sum.
expression = input("Enter a sum (e.g., 5+3): ")
parts = expression.split('+')
operand1 = int(parts[0].strip())
operand2 = int(parts[1].strip())
print(operand1 + operand2)
-
Character counting: Count digits and letters inside user-supplied text.
-
Relational concepts: Strings like
"example"and numbers like5relate through their corresponding types:strandint, which provide methods for conversion and manipulation. -
Dynamic template: Craft a message using user-provided name, location, and hobby.
name = input("Name: ")
place = input("Place: ")
hobby = input("Hobby: ")
print(f"Dear {name}, you enjoy {hobby} at {place}.")
-
Random verification code: Generate a code, display it, and match it against user input.
-
Content filter: Replace sensitive keywords (e.g., "spam", "phish") with asterisks.
-
Tabular data input: Prompt for username, password, and email repeatedly until "q" is entered, truncating each field to 20 characters, and finally display the collected data as a formatted table.
-
Encoding facts:"李杰" occupies 6 bytes in UTF-8 (3 bytes per Chinese character) and 4 bytes in GBK (2 bytes per character).
-
Range behavior: In Python 2,
rangecreates a list immediately; in Python 3, it returns a lazy iterator that generates values on demand. -
Simple quiz outputs:
a = "alex"
b = a.capitalize()
print(a) # alex
print(b) # Alex