Python String Practice Questions
Python String Practice Questions
To format a table of student names and scores using f-strings, ensure columns are aligned by specifying field widths. For instance, using f"{name:<20}{score:>5}" aligns names left and scores right with widths of 20 and 5 characters respectively. This creates a neat tabular display, ensuring names and scores are uniformly spaced across lines .
To validate if a string is a palindrome in Python, reverse the string and compare it to the original. You can reverse the string using slicing: `str[::-1]`. Then check if this reversed string matches the original string. For example, `s == s[::-1]` will return `True` if `s` is a palindrome .
To convert a user's full name entered in lowercase into title case in Python, utilize the string method `title()`. This method capitalizes the first letter of each word in the string. For example, if the input is 'john doe', the code `name.title()` will convert it to 'John Doe'. This can be used in a greeting by concatenating the greeting string with the converted name .
In Python, the `format()` method or f-strings can be used to format numbers with commas and two decimal places. For example, using `f"{number:,.2f}"` where `number` is your floating-point number will insert commas as thousand separators and round the number to two decimal places. An input of `12345.678` would output '12,345.68' .
To detect and remove special characters from a user's input string in Python, employ regular expressions. The `re` module provides a method `re.sub(pattern, repl, string)` which replaces all non-alphanumeric characters with an empty string, effectively removing them. The pattern '[^\w\s]' matches any special characters. For example, `re.sub('[^\w\s]', '', input_string)` will clean the input string .
To split a full name into first, middle, and last names in Python, use the `split()` method on spaces. If a middle name exists, it will be the middle item in the list after splitting. For example, splitting 'John F. Kennedy' on spaces produces ['John', 'F.', 'Kennedy']. You can then assign these parts accordingly. Handling optional middle names might involve additional checks on the list's length .
To make a string URL-friendly by replacing spaces with hyphens in Python, use the `replace()` method. This method allows you to replace all occurrences of a specified substring with another string. For example, `string.replace(' ', '-')` will convert 'hello world' to 'hello-world'. This is useful for creating URL slugs from strings that contain spaces .
To truncate a message to 50 characters and append '...' if it exceeds that length, use slicing in Python. Check the length of the string and slice it: `message[:50] + '...'` if `len(message) > 50`. This conditionally appends the ellipsis only when truncation is necessary, preserving the full message otherwise .
To extract the domain name from an email address in Python, you can use the `split()` method of strings. The email address is split at the '@' character, and the second element of the resulting list will be the domain. For example, for 'student@example.com', applying `email.split('@')[1]` will yield 'example.com' .
To join a list of words into a single sentence with commas and 'and' before the last word, first check that the list is not empty. For a list of words, `words`, use ', '.join on all elements except the last, combining the last element with 'and'. For example, ', '.join(words[:-1]) + ' and ' + words[-1] for a list like ['apple', 'banana', 'cherry'] results in 'apple, banana, and cherry' .