0% found this document useful (0 votes)
45 views2 pages

Python String Practice Questions

The document contains 20 scenario-based practice questions aimed at enhancing Python string manipulation and formatting skills. The questions cover a variety of tasks such as converting cases, extracting information, counting characters, and formatting outputs. These exercises are designed to simulate real-world string handling scenarios.

Uploaded by

adi9910119238
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views2 pages

Python String Practice Questions

The document contains 20 scenario-based practice questions aimed at enhancing Python string manipulation and formatting skills. The questions cover a variety of tasks such as converting cases, extracting information, counting characters, and formatting outputs. These exercises are designed to simulate real-world string handling scenarios.

Uploaded by

adi9910119238
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Scenario-Based Python String Practice

Questions
Below is a list of 20 scenario-based practice questions designed to help you improve your
Python string manipulation and formatting skills. These questions involve real-world tasks
like parsing, formatting, and modifying strings.

1. A user's full name is entered in lowercase. Convert it to title case and display a greeting.

2. Extract the domain name from an email address like 'student@[Link]'.

3. Given a sentence, count the number of vowels in it.

4. Take a paragraph of text and count how many times a specific word appears.

5. Replace all spaces in a string with hyphens to make it URL-friendly.

6. From a filename like 'report_final_2025.pdf', extract the base name without the extension.

7. Validate if a string is a palindrome (reads the same forward and backward).

8. Mask a phone number input, showing only the last 4 digits. E.g., '*******1234'.

9. Format a floating-point number to include commas and two decimal places (e.g.,
12345.678 → '12,345.68').

10. Check if a string starts with a specific prefix, such as 'Mr.' or 'Ms.'.

11. Join a list of words into a single sentence with commas and 'and' before the last word.

12. Truncate a message to the first 50 characters followed by '...' if it's too long.

13. Split a full name into first name, middle name (if any), and last name.

14. Convert a snake_case string into CamelCase format.

15. Detect and remove any special characters from a user's input string.

16. Center-align a name inside a decorative line of 30 characters using f-strings.

17. Count how many uppercase and lowercase letters are in a string.

18. Given a list of strings, find and return the longest one.

19. Print a table of student names and scores using proper alignment with f-strings.
20. Check if a string contains only digits and format it as a phone number (e.g., 1234567890
→ (123) 456-7890).

Common questions

Powered by AI

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' .

You might also like