Strings are sequence of Characters
In Python, specifically, strings are a sequence of Unicode Characters
* Creating Strings
* Accessing Strings
* Adding Chars to Strings
* Editing Strings
* Deleting Strings
* Operations on Strings
* String Functions
Creating Strings
Multiple ways to create string literals in Python programming
Explanation
- All these syntax variations create identical string objects in Python, demonstrating the flexibility of string literal notation using single quotes, double quotes, or triple quotes
- Triple quotes are particularly useful for multiline strings and preserve whitespace formatting automatically
- The str() constructor function can explicitly convert other data types to strings, though it's redundant when creating simple string literals
- Each method produces the same output when printed, showing that Python treats all these representations as equivalent string objects
- The choice between quote types often depends on readability preferences and whether the string contains quotation marks that need escaping
Output
String literal assignment and printing with double quotes in Python
Explanation
- The code assigns a string literal containing an apostrophe to the variable s using double quotes to avoid escaping the apostrophe
- Double quotes allow the string to contain single quotes without requiring escape characters
- The print function outputs the string content to the console
- This demonstrates Python's flexible string quoting options for handling special characters
Output
Accessing Substrings from a String
Accessing individual characters from a string using positive indexing in Python
Explanation
- The code initializes a string variable s with the value 'hello world'
- It uses positive indexing with [6] to access the character at position 6 in the string
- In Python string indexing, positions start at 0, so index 6 corresponds to the 7th character
- The character at index 6 is 'w' which is the first letter of 'world'
- This demonstrates how to retrieve specific characters from strings using their numerical positions
Output
Accessing the last character of a string using negative indexing in Python
Explanation
- Negative indexing allows accessing elements from the end of a sequence by using negative positions
- In Python, s[-1] refers to the last element of the string, where -1 represents the final position
- The string 'hello world' has 11 characters, so s[-1] returns 'd' which is the last character
- This indexing method works with any sequence type including strings, lists, and tuples
- Negative indices count backwards from -1 (last element) to -n (first element) for a sequence of length n
Output
This code snippet demonstrates how to extract a substring from a given string using slicing in Python.
Explanation
- The variable
sis assigned the string value 'hello world'. - The slicing operation
s[2:5]retrieves a substring starting from index 2 up to, but not including, index 5. - In this case, it extracts the characters 'llo' from the original string.
- The
printfunction outputs the resulting substring to the console.
Output
This code snippet demonstrates how to slice a string in Python to retrieve a substring.
Explanation
- The variable
sis assigned the string 'hello world'. - The slicing operation
s[2:]retrieves the substring starting from index 2 to the end of the string. - In this case, the output will be 'llo world', as it omits the first two characters 'h' and 'e'.
- The
printfunction displays the resulting substring to the console.
Output
This code snippet demonstrates how to slice a string in Python using specific start, stop, and step parameters.
Explanation
- The variable
sis assigned the string 'hello world'. - The slicing operation
s[0:6:2]extracts characters from index 0 to index 6, stepping through the string by 2 characters. - The resulting substring will include characters at indices 0, 2, and 4, which are 'h', 'l', and 'o', respectively.
- The
printfunction outputs the sliced result, which will be 'hlo'.
Output
This code snippet demonstrates how to slice a string in Python to exclude the last two characters.
Explanation
- The variable
sis assigned the string 'hello world'. - The slicing operation
s[:-2]retrieves all characters from the beginning of the string up to, but not including, the last two characters. - The
printfunction outputs the result of the slicing operation, which will be 'hello worl'. - This technique is useful for manipulating strings by removing unwanted characters from the end.
Output
This code snippet demonstrates how to reverse a substring using Python slicing.
Explanation
- The string
sis initialized with the value'hello world'. - The slicing operation
s[6:0:-1]extracts characters from index 6 to index 1 in reverse order. - The starting index 6 corresponds to the character
'w', and the ending index 0 corresponds to the character'h', but it does not include the character at index 0. - The result of the slicing operation is
'w ol', which is printed to the console. - The negative step
-1indicates that the slicing should proceed backwards through the string.
Output
This code snippet reverses a string in Python using slicing.
Explanation
- The variable
sis expected to be a string that is defined elsewhere in the code. - The slicing notation
s[::-1]creates a new string that is a reversed version ofs. - The
:indicates that we are slicing the entire string, while-1specifies the step, meaning it reads the string from the end to the beginning. - The
printfunction outputs the reversed string to the console.
Output
This code snippet retrieves the last five characters from a string variable s.
Explanation
- The code uses Python's slicing feature to access a portion of the string.
s[-5:]indicates that it starts from the fifth character from the end of the string and goes to the end.- If
shas fewer than five characters, it will return the entire string without error. - This is useful for extracting specific segments of a string, such as file extensions or trailing identifiers.
Output
This code snippet retrieves a reversed slice of a string or list from the end to a specified start index.
Explanation
- The code uses Python's slicing feature to access elements in reverse order.
s[-1:-6:-1]starts from the last element of the sequencesand moves backwards.- The slice stops before reaching the index
-6, effectively retrieving the last five elements in reverse. - If
shas fewer than six elements, the slice will return only the available elements in reverse. - This technique is useful for quickly accessing and manipulating the end portion of sequences.
Output
Editing and Deleting in String
Attempting to modify an immutable string in Python results in an error.
Explanation
- The variable
sis initialized with the string 'hello world'. - The code attempts to change the first character of the string from 'h' to 'H' using indexing.
- Python strings are immutable, meaning their contents cannot be changed after creation.
- This results in a
TypeError, as you cannot assign a new value to an indexed position in a string. - To modify a string, you must create a new string instead of trying to change the existing one.
Output
This code snippet demonstrates the deletion of a variable in Python.
Explanation
- The variable
sis initialized with the string value'hello world'. - The
delstatement is used to delete the variables, removing it from the current namespace. - Attempting to print
safter deletion will raise aNameErrorsincesno longer exists. - This illustrates how variable management and memory cleanup can be handled in Python.
Output
This code attempts to delete a slice from a string using negative indexing.
Explanation
- The variable
sis initialized with the string 'hello world'. - The
delstatement is used to attempt to delete a slice of the string from index -1 to -5. - However, negative slicing in Python does not work as intended here because the start index (-1) is greater than the stop index (-5).
- As a result, the string
sremains unchanged, and the output will still be 'hello world' when printed.
Output
Operators on Strings
* Arithmetic Operators
* Relational Operators
* Logical Operators
* Loops on Strings
* Membership Operators
This code snippet demonstrates string concatenation in Python.
Explanation
- The code uses the
printfunction to output a string to the console. - It concatenates three strings: 'Madhu', a space (' '), and 'Dadi'.
- The
+operator is used to combine the strings into a single output. - The final output will be "Madhu Dadi" displayed in the console.
Output
This code snippet demonstrates how to repeat a string multiple times in Python.
Explanation
- The
printfunction outputs the result to the console. - The string
'Madhu'is multiplied by5, which repeats it five times. - The output will be
MadhuMadhuMadhuMadhuMadhu, concatenating the string without any spaces. - This technique can be useful for generating repeated patterns or formatting output in a specific way.
Output
This code snippet prints a line of asterisks to create a visual separator.
Explanation
- The
printfunction is used to output text to the console. - The expression
'*'*50generates a string consisting of 50 asterisk characters. - This creates a visual separator that can be useful for organizing output in console applications.
- The output will be a single line of 50 asterisks, enhancing readability.
Output
This code snippet demonstrates a comparison between two city names using equality operator in Python.
Explanation
- The code uses the equality operator
==to compare two string values: 'Delhi' and 'Mumbai'. - It evaluates whether the two strings are identical.
- The result of the comparison will be
Falsesince 'Delhi' and 'Mumbai' are different strings. - This type of comparison is commonly used in conditional statements to control the flow of a program based on string equality.
Output
This code snippet demonstrates case-sensitive string comparison in Python.
Explanation
- The code checks if the string 'Delhi' is not equal to the string 'delhi'.
- The comparison is case-sensitive, meaning uppercase and lowercase letters are treated as different characters.
- As a result, the expression evaluates to
Truebecause 'D' (uppercase) is not the same as 'd' (lowercase).
Output
Comparing two strings lexicographically in Python using ASCII values
Explanation
- The code compares the strings 'Mumbai' and 'Pune' using the greater than operator (
>). - This comparison is performed based on the ASCII values of the characters in each string.
- In lexicographical order, the comparison checks the first character of each string; if they are equal, it moves to the next character.
- Since 'M' (ASCII 77) is greater than 'P' (ASCII 80), the expression evaluates to
False. - This type of comparison is useful for sorting or ordering strings in Python.
Output
This code snippet compares two city names lexicographically in Python.
Explanation
- The code uses the greater-than operator (
>) to compare the strings 'Pune' and 'Mumbai'. - String comparison in Python is based on lexicographical order, which is determined by the Unicode values of the characters.
- In this case, 'P' in 'Pune' has a higher Unicode value than 'M' in 'Mumbai', resulting in a
Trueevaluation. - The output of this comparison can be used in conditional statements or logical expressions within a program.
Output
Understanding string comparison in Python based on ASCII values
Explanation
- Python compares strings lexicographically using the ASCII values of their characters.
- In this case, 'P' has an ASCII value of 80, while 'p' has an ASCII value of 112.
- Since 80 is less than 112, the comparison returns False, indicating that 'Pune' is not greater than 'pune'.
- This behavior highlights the case sensitivity in string comparisons in Python.
Output
Python logical AND operator behavior with string values
Explanation
- The expression 'hello' and 'world' uses Python's logical AND operator which evaluates expressions from left to right
- Since 'hello' is a non-empty string (truthy), Python continues evaluation and moves to the second operand 'world'
- The AND operator returns the last evaluated operand when all previous operands are truthy, so it returns 'world'
- This demonstrates Python's short-circuit evaluation behavior where subsequent expressions are only evaluated when needed
- The result shows how logical operators can be used to select between values based on truthiness rather than just boolean logic
Output
Python logical OR operator behavior with string literals
Explanation
- The expression evaluates to 'hello' because the OR operator returns the first truthy value it encounters
- In Python, non-empty strings are considered truthy, so 'hello' is evaluated as True
- Since 'hello' is truthy, the OR operator doesn't need to evaluate 'world' and immediately returns 'hello'
- This demonstrates short-circuit evaluation where the second operand is only evaluated if needed
- The result shows how Python's OR operator works with string objects rather than simply returning boolean values
Output
Python logical AND operator behavior with empty string and non-empty string
Explanation
- The expression uses Python's short-circuit evaluation where
''(empty string) is evaluated as falsy - Since the first operand is falsy, Python immediately returns the first operand without evaluating the second part
- This demonstrates how Python's
andoperator doesn't always evaluate both operands when the result can be determined from the first - The result of
'' and 'world'is''(the empty string) rather than'world' - This behavior follows Python's truthiness rules where empty strings are considered falsy values
Output
Python logical OR operator with empty string and non-empty string evaluation
Explanation
- The expression uses Python's short-circuit evaluation where
''(empty string) is falsy and'world'(non-empty string) is truthy - Since the first operand
''evaluates to False, Python continues evaluating and returns the second operand'world' - This demonstrates how the
oroperator returns the first truthy value it encounters, or the last value if all are falsy - Empty strings, None, zero, and other "falsy" values are commonly used in conditional logic for default value assignment
- The result of this expression is the string 'world' which can be useful for setting fallback values in configuration or user input handling
Output
This code snippet demonstrates the use of the logical NOT operator in Python to evaluate a string.
Explanation
- The
notoperator inverts the truth value of the expression that follows it. - In this case, the expression is the string
'hello', which is considered truthy in Python. - Therefore,
not 'hello'evaluates toFalse. - This can be useful for conditional checks where you want to determine if a value is falsy.
- Strings that are empty (e.g.,
'') would evaluate toTruewhen negated withnot.
Output
Evaluating the truthiness of an empty string in Python
Explanation
- The expression
not ''checks the boolean value of an empty string. - In Python, an empty string is considered falsy, meaning it evaluates to
False. - The
notoperator negates the falsy value, resulting inTrue. - This can be useful for conditionally executing code based on the presence or absence of string content.
Output
This code snippet demonstrates how to iterate over each character in a string using a loop.
Explanation
- The
forloop iterates through each character in the string'hello'. - The variable
itakes on the value of each character in the string during each iteration. - The
print(i)statement outputs the current character to the console. - This approach is useful for processing or manipulating each character individually.
Output
This code snippet demonstrates a loop that prints a specific string for each character in a given string.
Explanation
- The
forloop iterates over each character in the string 'delhi'. - For each iteration, it executes the
printfunction. - The output will be the string 'pune' printed five times, once for each character in 'delhi'.
- This code does not utilize the loop variable
i, making it a simple repetition of the print statement.
Output
This code checks for the presence of a character in a string using membership operators.
Explanation
- The code uses the
inoperator to determine if the character'd'exists within the string'delhi'. - If the character is found, the expression evaluates to
True; otherwise, it evaluates toFalse. - Membership operators like
inare commonly used for string searching and list membership checks in Python. - This snippet demonstrates a simple yet effective way to perform substring checks in Python.
Output
This code checks for the absence of a character in a string.
Explanation
- The expression checks if the character 'd' is not present in the string 'Delhi'.
- It evaluates to a boolean value:
Trueif 'd' is absent andFalseif it is present. - This is useful for validating input or filtering data based on character presence.
- The check is case-sensitive, meaning 'D' (uppercase) would not be considered the same as 'd' (lowercase).
Output
Common Functions
* len
* max
* min
* sorted
This code calculates the length of a given string in Python.
Explanation
- The
len()function is a built-in Python function that returns the number of items in an object. - In this case, it is used to determine the number of characters in the string
'hello world'. - The output will be an integer representing the total count of characters, including spaces.
- This function can be applied to various data types, such as lists and tuples, to find their lengths as well.
Output
Determine the maximum ASCII character from a given string in Python
Explanation
- The
max()function is used to find the character with the highest ASCII value in the string 'hello world'. - It evaluates each character in the string based on its ASCII representation.
- In this case, the function will return 'w', as it has the highest ASCII value among the characters in the string.
- This method can be applied to any string to find the character with the maximum ASCII value.
Output
This code snippet finds the minimum character in a string based on ASCII values.
Explanation
- The
min()function is used to determine the smallest item in an iterable. - In this case, the iterable is the string
'hello world'. - The function evaluates each character's ASCII value to find the minimum.
- The result will be the character with the lowest ASCII value, which is a space
' '. - This demonstrates how Python handles string comparisons based on ASCII ordering.
Output
This code sorts the characters of a string in ascending ASCII order.
Explanation
- The
sorted()function takes an iterable, in this case, the string 'hello world'. - It returns a list of characters sorted according to their ASCII values.
- Spaces are sorted before letters since they have a lower ASCII value.
- The output will be a list of characters, including duplicates, sorted alphabetically.
- This operation does not modify the original string but creates a new sorted list.
Output
Capitalize / Title / Upper / Lower / Swapcase
This code snippet demonstrates how to capitalize the first letter of a string in Python.
Explanation
- The variable
sis assigned the string value'hello world'. - The
capitalize()method is called on the strings, which returns a new string with the first character converted to uppercase and the rest to lowercase. - The original string
sremains unchanged since strings in Python are immutable. - The result of
s.capitalize()is not stored or printed, so it will not be visible unless assigned to a variable or printed directly.
Output
Transforming a string to title case using Python's string method
Explanation
- The
title()method is called on a strings, which converts the first character of each word to uppercase and the remaining characters to lowercase. - This method is useful for formatting titles or headings where proper capitalization is required.
- If the string contains punctuation or special characters, they are treated as word boundaries.
- The method does not modify the original string; it returns a new string with the title case applied.
Output
Convert a string to uppercase using Python's built-in method.
Explanation
- The
upper()method is called on a strings. - It returns a new string where all lowercase letters in
sare converted to uppercase. - This method does not modify the original string, as strings in Python are immutable.
- It is useful for standardizing text input or for case-insensitive comparisons.
Output
This code snippet converts a string to lowercase in Python.
Explanation
- The
lower()method is called on a string objects. - It returns a new string where all uppercase letters in
sare converted to their lowercase counterparts. - This method does not modify the original string
s, as strings in Python are immutable. - It is useful for case-insensitive comparisons or formatting text uniformly.
Output
This code snippet demonstrates how to swap the case of each character in a string.
Explanation
- The
swapcase()method is called on the string'HeLlO WorLD'. - It converts all uppercase letters to lowercase and all lowercase letters to uppercase.
- The output of this operation will be
'hElLo wORld'. - This method is useful for text manipulation where case inversion is required.
Output
Count / Find / Index
Counting occurrences of a substring in a string using Python's count method
Explanation
- The code snippet uses the
countmethod of a string to find the number of times the substring'i'appears in the string'my name is madhu'. - It returns an integer value representing the count of the specified substring.
- In this case, the output will be
1, as the letter'i'appears once in the given string. - This method is case-sensitive, meaning it will only count lowercase
'i'and not uppercase'I'. - The
countmethod is useful for string analysis and manipulation tasks in Python.
Output
This code counts the occurrences of the letter 'm' in a given string.
Explanation
- The string 'my name is madhu' is defined and the method
count()is called on it. - The
count()method takes a substring as an argument, in this case, the letter 'm'. - It returns the total number of times 'm' appears in the string, which is 3.
- This method is case-sensitive, meaning it will only count lowercase 'm' and not uppercase 'M'.
- The result can be used for various purposes, such as data analysis or string manipulation.
Output
This code snippet demonstrates how to locate a substring within a string in Python.
Explanation
- The
find()method is called on the string'my name is madhu'. - It searches for the substring
'madhu'within the main string. - If the substring is found,
find()returns the starting index of the substring; otherwise, it returns-1. - In this case, the output will be
11, as'madhu'starts at index 11 in the original string.
Output
This code snippet demonstrates how to locate a substring within a string in Python.
Explanation
- The
find()method is called on the string'my name is madhu'. - It searches for the substring
'is'within the main string. - If the substring is found,
find()returns the index of its first occurrence; otherwise, it returns-1. - In this case, the method will return
8, as'is'starts at the 8th index of the string.
Output
This code snippet demonstrates how to search for a substring within a string in Python.
Explanation
- The
find()method is called on the string'my name is madhu'. - It searches for the substring
'x'within the main string. - If the substring is found,
find()returns the index of its first occurrence; otherwise, it returns-1. - In this case, since
'x'is not present in the string, the output will be-1.
Output
This code snippet finds the position of a substring within a string in Python.
Explanation
- The
index()method is called on the string'my name is madhu'. - It searches for the substring
'is'within the main string. - The method returns the starting index of the first occurrence of the substring, which is
8in this case. - If the substring is not found, it raises a
ValueError. - This method is case-sensitive, meaning it distinguishes between uppercase and lowercase letters.
Output
Understanding the difference between string methods index and find in Python
Explanation
- The code attempts to find the index of the character 'x' in the string 'my name is madhu'.
- The
indexmethod raises aValueErrorif the specified substring is not found, unlikefind, which returns -1. - This snippet highlights the behavior of
indexwhen the substring does not exist in the string. - It serves as a reminder to handle exceptions when using
indexto avoid runtime errors.
Output
endswith / startswith
This code checks if a string ends with a specified substring.
Explanation
- The
endswith()method is a built-in string function in Python. - It returns
Trueif the string ends with the specified suffix, andFalseotherwise. - In this case, it checks if the string
'my name is madhu'ends with the substring'madhu'. - The result of this check will be
Truesince the string indeed ends with'madhu'.
Output
Testing string suffix matching with the endswith method in Python
Explanation
- The code uses Python's built-in string method
endswith()to check if a string ends with a specific substring - It evaluates whether the string "my name is madhu" concludes with the character sequence "aa"
- The method returns a boolean value (True or False) based on the match result
- In this case, it will return False since the string ends with "u" not "aa"
- This technique is commonly used for validating file extensions or filtering strings by their ending characters
Output
Python string startswith method checks if a string begins with a specified prefix character
Explanation
- The code uses the startswith() method to determine if the string 'my name is madhu' begins with the letter 'm'
- This method returns a boolean value (True or False) based on whether the string starts with the specified substring
- In this case, it will return True since the string indeed starts with 'm'
- The startswith() method is case-sensitive, so it would return False for 'M' even if the string contained uppercase letters
- This functionality is commonly used for data validation, filtering, or conditional logic based on string prefixes
Output
Checking if a string begins with a specific substring using Python's startswith method
Explanation
- The code uses the built-in startswith() method to determine if the string 'my name is madhu' begins with the substring 'madhu'
- This method returns a boolean value (True or False) based on whether the string starts with the specified prefix
- In this case, since 'my name is madhu' does not start with 'madhu' (it starts with 'my'), the result will be False
- The startswith() method is commonly used for string validation and pattern matching in text processing tasks
- This approach is more efficient than manually checking string indices when verifying string prefixes
Output
Format
This code snippet demonstrates how to format strings using the format method in Python.
Explanation
- The variables
nameandgenderare initialized with the values 'madhu' and 'male', respectively. - The
formatmethod is used to insert the values ofnameandgenderinto the string template. - The placeholders
{}in the string are replaced by the corresponding values from theformatmethod in the order they are provided. - The resulting string will be 'Hi my name is madhu and I am a male'.
Output
This code demonstrates string formatting in Python using the format method.
Explanation
- The variables
nameandgenderare defined with string values. - The
formatmethod is used to insert these variables into a string template. - The placeholders
{1}and{0}correspond to the second and first arguments of theformatmethod, respectively. - The resulting string will read "Hi my name is madhu and I am a male".
Output
isalnum / isalpha / isdigit / isidentifier
This code checks if the string contains only alphanumeric characters.
Explanation
- The method
isalnum()is called on the string'madhu245'. - It returns
Trueif all characters in the string are either letters or numbers. - If the string contains any spaces or special characters, it would return
False. - This is useful for validating input where only alphanumeric characters are allowed.
Output
This code checks if the string contains only alphanumeric characters.
Explanation
- The
isalnum()method is called on the string'madhu245%'. - It returns
Trueif all characters in the string are alphanumeric (letters and numbers) and there is at least one character; otherwise, it returnsFalse. - In this case, the presence of the '%' character makes the string non-alphanumeric.
- Therefore, the output of this code will be
False.
Output
This code checks if the string contains only alphabetic characters.
Explanation
- The method
isalpha()is called on the string'madhu245'. - It returns
Trueif all characters in the string are alphabetic and there is at least one character; otherwise, it returnsFalse. - In this case, since the string contains numeric characters ('245'), the method will return
False. - This function is useful for validating input that should only consist of letters.
Output
This code checks if the string contains only alphabetic characters.
Explanation
- The method
isalpha()is called on the string'madhu'. - It returns
Trueif all characters in the string are alphabetic and there is at least one character. - If the string contains any non-alphabetic characters (like numbers or symbols), it returns
False. - This method is useful for validating input where only letters are allowed.
Output
This code checks if the string consists solely of digits.
Explanation
- The method
isdigit()is called on the string'madhu245'. - It returns
Trueif all characters in the string are digits and there is at least one character; otherwise, it returnsFalse. - In this case, since the string contains alphabetic characters, the method will return
False. - This function is useful for validating input where only numeric values are expected.
Output
This code checks if a string consists solely of numeric characters.
Explanation
- The method
isdigit()is called on the string'123'. - It returns
Trueif all characters in the string are digits and there is at least one character. - In this case, since
'123'contains only numeric characters, the output will beTrue. - This method is useful for validating user input or processing data that should be numeric.
Output
This code checks if a string is a valid Python identifier.
Explanation
- The
isidentifier()method is a built-in string method in Python. - It returns
Trueif the string consists of valid characters for a Python identifier, which includes letters, digits, and underscores. - Identifiers must not start with a digit; hence, '1name' is invalid.
- In this case, the method will return
Falsebecause '1name' starts with a digit. - This can be useful for validating user input or variable names in programming.
Output
This code checks if the string 'name1' is a valid Python identifier.
Explanation
- The
isidentifier()method is a built-in string function in Python. - It returns
Trueif the string meets the criteria for a valid identifier, which includes starting with a letter or underscore and containing only alphanumeric characters and underscores. - In this case, 'name1' is a valid identifier, so the method will return
True. - This function is useful for validating user input or dynamically generated variable names in Python.
Output
This code checks if the string 'first_name' is a valid Python identifier.
Explanation
- The
isidentifier()method is a built-in string method in Python. - It returns
Trueif the string consists of valid characters for a Python identifier, which includes letters, digits, and underscores. - Identifiers must not start with a digit and cannot contain spaces or special characters.
- This method is useful for validating variable names or function names in Python code.
Output
This code checks if the string 'first-name' is a valid Python identifier.
Explanation
- The
isidentifier()method is a built-in string function in Python. - It returns
Trueif the string consists of valid identifier characters and follows the rules for naming identifiers in Python. - Identifiers must start with a letter or an underscore and can contain letters, digits, and underscores, but not hyphens.
- In this case, 'first-name' contains a hyphen, making it an invalid identifier, so the method will return
False.
Output
Split / Join
This code snippet splits a string into a list of words.
Explanation
- The
split()method is called on the string'hi my name is madhu'. - It divides the string at each space, creating a list of individual words.
- The resulting list will be
['hi', 'my', 'name', 'is', 'madhu']. - This method is useful for processing text data by separating words for further analysis or manipulation.
Output
This code splits a string into a list based on the specified delimiter.
Explanation
- The
split('i')method is called on the string'hi my name is madhu'. - It divides the string at each occurrence of the character
'i'. - The result is a list containing the segments of the string that were separated by
'i'. - In this case, the output will be
['h', ' my name ', 's madhu']. - This method is useful for breaking down strings into manageable parts for further processing.
Output
This code snippet concatenates a list of strings into a single string with spaces in between.
Explanation
- The
join()method is called on a string containing a single space (" "), which serves as the separator. - The method takes an iterable (in this case, a list of strings) and combines its elements into one string.
- Each element in the list
['hi', 'my', 'name', 'is', 'madhu']is separated by a space in the resulting string. - The output of this operation will be:
"hi my name is madhu".
Output
This code snippet concatenates a list of strings into a single string separated by hyphens.
Explanation
- The
join()method is called on the string"-"which serves as the separator. - The method takes a list of strings
['hi', 'my', 'name', 'is', 'madhu']as an argument. - Each element in the list is combined into one string, with each element separated by a hyphen.
- The resulting string will be
"hi-my-name-is-madhu". - This technique is useful for creating formatted strings from lists of words or phrases.
Output
Replace
This code snippet demonstrates how to replace a substring within a string in Python.
Explanation
- The
replace()method is called on a string to substitute occurrences of a specified substring. - In this case, the substring 'madhu' is replaced with 'dadi'.
- The method returns a new string with the specified replacements made, leaving the original string unchanged.
- If the substring to be replaced is not found, the original string is returned without any modifications.
Output
This code snippet demonstrates how to replace a substring in a string using Python's replace method.
Explanation
- The
replacemethod is called on the string'hi my name is madhu'. - It attempts to replace all occurrences of the substring
'aaaa'with'dadi'. - Since the substring
'aaaa'does not exist in the original string, the output remains unchanged. - The method returns a new string with the specified replacements, but in this case, it returns the original string.
- This illustrates how the
replacemethod functions when the target substring is not found.
Output
Strip
This code snippet demonstrates how to remove trailing whitespace from a string in Python.
Explanation
- The
strip()method is called on the string'Madhu '. - It removes any leading and trailing whitespace characters from the string.
- The result of this operation will be the string
'Madhu'without any extra spaces. - This method is useful for cleaning up user input or formatting strings for display.
Output
This code snippet removes trailing hyphens from a string in Python.
Explanation
- The
strip()method is used to remove specified characters from both ends of a string. - In this case, the character to be removed is the hyphen (
-). - The input string is
'Madhu----------', which contains trailing hyphens. - The result of the operation will be
'Madhu', as all hyphens at the end are stripped away. - This method does not modify the original string but returns a new string with the specified characters removed.
Output
Example Programs
Calculate the length of a string manually using a loop in Python
Explanation
- The code prompts the user to input a string and stores it in the variable
s. - A counter variable is initialized to zero to keep track of the number of characters in the string.
- A for loop iterates over each character in the string, incrementing the counter by one for each character encountered.
- Finally, the total count of characters is printed as the length of the string.
Output
Extracting the username from an email address using Python
Explanation
- The code prompts the user to input an email address.
- It uses the
findmethod to locate the position of the '@' character in the email string. - The username is extracted by slicing the string from the start up to the position of the '@' character.
- Finally, it prints the extracted username to the console.
Output
Python script to count character occurrences in user-provided text strings
Explanation
- Takes two string inputs from the user: the main string to analyze and the specific character to search for
- Initializes a counter variable to zero before beginning the frequency calculation process
- Iterates through each character in the input string using a for loop to compare against the target character
- Increments the counter each time a matching character is found in the string
- Displays the final frequency count of the specified character within the provided string
Output
Python script to calculate character or substring occurrence frequency in user input text
Explanation
- The code prompts users to enter a string and a search term through interactive input prompts
- It uses the built-in count() method to determine how many times the search term appears in the input string
- The result is displayed as a simple frequency count showing how many occurrences were found
- This approach works for both single characters and multi-character substrings within the text
- The solution demonstrates basic string manipulation and user interaction in Python programming
Output
Python program to remove all occurrences of a specified character from user input string
Explanation
- The code prompts users to enter a string and specify which character they want to remove from it
- It initializes an empty result string and iterates through each character in the input string
- During iteration, it only appends characters to result that don't match the target removal character
- All occurrences of the specified character are eliminated from the final output string
- The program demonstrates basic string manipulation and character filtering techniques
Output
This Python code checks if a user-input string is a palindrome.
Explanation
- The program prompts the user to enter a string and stores it in the variable
s. - It compares the original string
swith its reverses[::-1]using slicing. - If both strings are identical, it prints 'Palendrome'; otherwise, it prints 'Not Palendrome'.
- The code effectively demonstrates string manipulation and conditional statements in Python.
Output
This Python code checks if a string is a palindrome by comparing characters from both ends.
Explanation
- The program prompts the user to input a string and initializes a flag variable to track palindrome status.
- It iterates through the first half of the string, comparing each character with its corresponding character from the end.
- If any characters do not match, the flag is set to False, and the loop breaks early for efficiency.
- After the loop, it checks the flag and prints whether the string is a palindrome or not.
- Note that there is a typo in the output messages; "Palendrome" should be corrected to "Palindrome".
Output
Counting words in a string without using the split method in Python
Explanation
- The program prompts the user to input a string and initializes an empty list
Land a temporary stringtempto hold characters. - It iterates through each character in the input string; if the character is not a space, it appends it to
temp. - When a space is encountered, the current
tempstring is added to the listL, andtempis reset for the next word. - After the loop, the last word (if any) is appended to the list
Lto ensure it is included. - Finally, the list
L, which contains all the words from the input string, is printed.
Output
Convert a string to title case manually in Python without using built-in functions
Explanation
- The program prompts the user to input a string.
- It initializes an empty list
Lto store the modified words. - The string is split into individual words, and each word is processed to capitalize the first letter and convert the rest to lowercase.
- Each modified word is appended to the list
L. - Finally, the list is joined into a single string with spaces and printed.
Output
Converting an integer to a string representation in Python
Explanation
- The program prompts the user to input an integer, which is then stored in the variable
number. - A string
digitscontaining all possible digit characters is defined for easy access during conversion. - An empty string
resultis initialized to build the final string representation of the integer. - A while loop iterates as long as
numberis not zero, extracting the last digit using modulus and prepending it toresult. - Finally, the constructed string representation of the integer is printed.
Output
Problem 1 - Print the following pattern. Write a program to use for loop to print the following reverse number pattern.
This Python code generates a reverse number triangle based on user-defined rows.
Explanation
- The code prompts the user to input the number of rows for the triangle.
- It uses a nested loop where the outer loop iterates over the range of rows, and the inner loop counts down from the current row number to 1.
- The
print(j, end=' ')statement prints the numbers in a single line, separated by spaces. - After each inner loop completes,
print()is called to move to the next line, creating the triangle shape. - The result is a right-aligned triangle of numbers that decreases in length with each row.
Output
Problem 2: Print the following pattern.
This code generates a pyramid pattern of asterisks followed by an inverted pyramid pattern.
Explanation
- The user is prompted to input the number of rows for the pyramid pattern.
- The first nested loop creates an ascending pyramid by printing an increasing number of asterisks for each row.
- The second nested loop generates a descending inverted pyramid by printing a decreasing number of asterisks for each subsequent row.
- The
end=' 'parameter in theprintfunction ensures that asterisks are printed on the same line with a space in between. - Each
print()call without arguments moves the cursor to the next line after completing a row of asterisks.
Output
Problem 3:Write a program to pring the following pattern
This Python code generates a right-aligned triangle pattern using asterisks.
Explanation
- The variable
rowsis initialized to 6, representing the maximum number of rows for the triangle. - A
forloop iterates from 1 torows, incrementingiwith each iteration to control the number of asterisks printed. - Inside the loop, spaces are printed to align the asterisks to the right by using
' '*rows. - The
print('* '*i)statement printsiasterisks followed by a space, creating the triangle effect. - The
rowsvariable is decremented in each iteration to reduce the number of leading spaces for the next row.
Output
Problem 4:Write a program to print the following pattern
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
This code generates a right-aligned triangular pattern of numbers in descending order.
Explanation
- The variable
rowsis set to 5, determining the number of lines in the output. - The outer loop iterates from 1 to
rows, controlling the number of lines printed. - The inner loop counts down from the current line number
ito 1, printing each number followed by a space. - The
end=' 'parameter in theprintfunction prevents a newline after each number, allowing them to be printed on the same line. - After each inner loop completes,
print()is called to move to the next line for the subsequent row.
Output
Problem 5: Write a Python Program to Find the Sum of the Series till the nth term:
1 + x^2/2 + x^3/3 + … x^n/n n will be provided by the user
This code calculates a mathematical series involving powers of x and displays the series and its sum.
Explanation
- Initializes variables
xandnwith values 10 and 5, respectively. - Uses a loop to compute the sum of the series defined by the formula ( \sum \frac{x^i}{i} ) for ( i ) ranging from 2 to ( n ).
- Constructs a string representation of the series in the format
x^i/ifor each term and appends it to the strings. - After the loop, it prints the constructed series string without the trailing plus sign and the final computed sum.
Output
Problem 6: The natural logarithm can be approximated by the following series.
If x is input through the keyboard, write a program to calculate the sum of the first seven terms of this series.
This Python code calculates a mathematical series and formats its representation as a string.
Explanation
- Initializes variables
xandn, wherexis a constant andndetermines the number of terms in the series. - Uses a loop to iterate from 1 to
n, calculating each term of the series based on the formula(1/i)*((x-1)/x)**iand accumulating the sum. - Constructs a string
sthat represents the series in a formatted manner, appending each term during the loop. - After the loop, the code prints the formatted string of the series without the trailing plus sign and the final computed sum of the series.
Output
Problem 7 - Find the sum of the series upto n terms.
Write a program to calculate the sum of series up to n term. For example, if n =5 the series will become 2 + 22 + 222 + 2222 + 22222 = 24690. Take the user input and then calculate. And the output style should match which is given in the example.
Example 1:
Input:
Output:
This code calculates the sum of a series of numbers generated by a specific pattern.
Explanation
- The user is prompted to input the number of terms (
n) to generate in the series. - The series starts with the number 2 and each subsequent number is formed by multiplying the previous number by 10 and adding 2 (e.g., 2, 22, 222, etc.).
- A loop iterates
ntimes to print each number in the series, formatting the output with a '+' sign between numbers except for the last one. - The cumulative sum of the generated numbers is calculated and stored in the variable
sum. - Finally, the total sum is printed after the loop completes.
Output
###Problem 8: Write a program to print all the unique combinations of 1,2,3 and 4
Output:
This code generates all possible combinations of four nested loops with specified ranges.
Explanation
- The outer loop iterates
ifrom 1 to 3, creating three iterations. - The second loop iterates
jfrom 1 to 4, resulting in four iterations for eachi. - The third loop iterates
kfrom 1 to 4, adding another four iterations for each combination ofiandj. - The innermost loop iterates
mfrom 1 to 4, producing four iterations for each combination ofi,j, andk. - The
printstatement outputs the current values ofi,j,k, andm, resulting in a total of 3 * 4 * 4 * 4 = 192 combinations.
Output
###Problem 9: Write a program that will take a decimal number as input and prints out the binary equivalent of the number
This code converts a decimal number to its binary representation and prints it.
Explanation
- The user is prompted to input a decimal number, which is then converted to an integer.
- A while loop is used to repeatedly divide the number by 2, storing the remainder (0 or 1) in a list called
binary. - The loop continues until the number becomes zero, effectively building the binary representation in reverse order.
- After the loop, a for loop iterates over the reversed
binarylist to print the binary digits in the correct order without spaces. - The output is a direct representation of the input decimal number in binary format.
Output
###Problem 10: Write a program that will take 2 numbers as input and prints the LCM and HCF of those 2 numbers
This Python code calculates the Least Common Multiple (LCM) and Highest Common Factor (HCF) of two user-input numbers.
Explanation
- The code prompts the user to input two integers,
xandy. - It determines the greater of the two numbers to start the LCM calculation.
- A while loop increments the greater number until it finds a value that is divisible by both
xandy, which is the LCM. - The code then identifies the smaller of the two numbers to calculate the HCF using a for loop that checks for common divisors.
- Finally, it prints the calculated LCM and HCF values to the console.
Output
Problem 11: Create Short Form from initial character
Given a string create short form ofthe string from Initial character. Short form should be capitalised.
Example:
Input:
Output:
This code generates an acronym from a given string by capitalizing the first letter of each word.
Explanation
- The input string is defined as 'Data science mentorship program'.
- An empty string
resis initialized to store the acronym. - The code splits the input string into individual words and iterates through each word.
- For each word, it takes the first letter, converts it to uppercase, and appends it to the
resstring. - Finally, the acronym is printed, which in this case would be 'DSMP'.
Output
###Problem 12: Append second string in the middle of first string
Input:
Output:
This code combines two input strings by inserting one into the middle of the other.
Explanation
- The code prompts the user to input two strings,
s1ands2. - It calculates the midpoint of the first string
s1usinglen(s1)/2. - The first half of
s1is concatenated withs2, followed by the second half ofs1. - The final output is a new string that integrates
s2into the middle ofs1.
Output
Problem 13:Given string contains a combination of the lower and upper case letters. Write a program to arrange the characters of a string so that all lowercase letters should come first.
Given:
str1 = PyNaTive
Expected Output:
yaivePNT
This code separates lowercase and uppercase letters from a string and concatenates them.
Explanation
- The string
sis initialized with the value 'PyNaTive'. - Two empty strings,
upperandlower, are created to store uppercase and lowercase characters, respectively. - A for loop iterates through each character in the string
s. - Inside the loop, the
islower()method checks if the character is lowercase; if true, it appends the character tolower, otherwise toupper. - Finally, the concatenated result of
lowerfollowed byupperis printed, resulting in 'ativePYN'.
Output
Problem 14:Take a alphanumeric string input and print the sum and average of the digits that appear in the string, ignoring all other characters.
Input:
hel123O4every093
Output:
This code calculates the sum and average of all digits in a given string.
Explanation
- Initializes a string
scontaining alphanumeric characters. - Uses a loop to iterate through each character in the string.
- Checks if the character is a digit using the
isdigit()method. - If it is a digit, adds its integer value to
sumand increments thecountof digits found. - Finally, prints the total sum of the digits and their average by dividing
sumbycount.
Output
Problem 15: Removal of all characters from a string except integers
Given:
Expected Output:
This code extracts all numeric characters from a given string.
Explanation
- The string
scontains a mix of text and numbers. - An empty string
resis initialized to store the extracted digits. - A for loop iterates through each character in the string
s. - The
isdigit()method checks if the character is a digit; if true, it appends the digit tores. - Finally, the code prints the concatenated string of digits, which in this case would be '2510'.
Output
Problem 16: Check whether the string is Symmetrical.
Statement: Given a string. the task is to check if the string is symmetrical or not. A string is said to be symmetrical if both the halves of the string are the same.
Example 1:
Input
Output
Python program to check if a string is symmetric by comparing its two halves
Explanation
- The code takes user input and determines if the string has even or odd length to split it into two equal parts
- For even-length strings, it splits exactly in half using integer division, while for odd-length strings it skips the middle character
- It compares the first half (s1) with the second half (s2) character by character
- If both halves are identical, it prints "Symmetric", otherwise it prints "Not Symmetric"
- The logic handles both even and odd length strings correctly by adjusting the slicing indices accordingly
Output
Problem 17: Reverse words in a given String
Statement: We are given a string and we need to reverse words of a given string.
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Reversing word order in a string using list manipulation and slicing
Explanation
- The code initializes a string variable s containing "My name is Madhu Dadi" and an empty list L
- It iterates through each word in the string using split() method and appends each word to the list L
- The list L is reversed using slice notation [::-1] which creates a new list with elements in reverse order
- Finally, it joins the reversed list elements back into a string with spaces and prints the result
- The output displays the words in reverse order: "Dadi Madhu is name My"
Output
Problem 18: Find uncommon words from two Strings.
Statement: Given two sentences as strings A and B. The task is to return a list of all uncommon words. A word is uncommon if it appears exactly once in any one of the sentences, and does not appear in the other sentence. Note: A sentence is a string of space-separated words. Each word consists only of lowercase letters.
Example 1:
Input:
Output:
Python script to find unique words between two string variables using list comprehension and conditional logic
Explanation
- The code initializes two string variables containing space-separated words and an empty list to store results
- It iterates through each word in the first string (A) and adds words to the result list only if they don't exist in the second string (B) and aren't already in the result list
- The code then processes each word in the second string (B) similarly, adding words that don't appear in the first string (A) and aren't already in the result list
- The final output displays a list of words that are unique to each string, excluding common words and duplicates
- This approach effectively identifies the symmetric difference between the two sets of words from the strings
Output
Problem 19: Word location in String.
Statement: Find a location of a word in a given sentence.
Example 1:
Input:
Output:
Note- Don't use index/find functions
This code snippet finds the position of a specific word in a given string.
Explanation
- The string
scontains a sentence where the search for the word occurs. - The variable
wordholds the target word to find within the string. - A loop iterates through each word in the split version of the string, incrementing the position counter
poswith each iteration. - If the current word matches the target word, the loop breaks, and the position of the word is printed.
- The output will be the 1-based index of the first occurrence of the word in the sentence.
Output
Problem 20: Write a program that can remove all the duplicate characters from a string. User will provide the input.
This code removes duplicate characters from a string while preserving the original order.
Explanation
- A string
sis defined containing multiple characters, some of which are repeated. - An empty string
resis initialized to store unique characters. - The code iterates through each character
iin the strings. - If the character
iis not already inres, it is appended tores, ensuring only unique characters are retained. - Finally, the unique characters are printed in the order they first appeared in the original string.
Output
Next in this series: Time Complexity in Python: Measure & Optimize Your Code →

