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
Example 1
Explanation
- The code assigns the string value 'hello' to the variable
susing different syntaxes including single quotes, double quotes, and triple quotes for both single and multi-line strings. - It also demonstrates the use of the
str()function to convert an object to a string, though in this case, it's redundant since 'hello' is already a string. - The
print()function is used to output the value ofsto the console. - Expected output is the string
helloprinted on the console. - The use of triple quotes allows for multiline strings, although in this example, they contain only a single line.
Output
Example 2
Explanation
- The code assigns a string value to the variable
s, which includes an apostrophe. - It uses double quotes around the string to avoid syntax errors caused by the apostrophe.
- The
print()function is called to display the value ofson the console. - The expected output is the string
it's raining outside. - There are no side effects other than printing the string to the console.
Output
Accessing Substrings from a String
Example 3
Explanation
- The code accesses a character in the string
susing positive indexing. s[6]retrieves the character at index 6 of the strings.- The string
sis 'hello world', where indexing starts from 0. - The character at index 6 is a space (' ').
- The
printfunction outputs the space character to the console.
Output
Example 4
Explanation
- The code accesses the last character of the string
susing negative indexing. - It uses the
print()function to display the accessed character. - The expected output is
d, which is the last character of the string'hello world'. - Negative indexing in Python allows access to elements from the end of a sequence, where
-1refers to the last element. - This code demonstrates how to use negative indices to retrieve specific characters from a string.
Output
Example 5
Explanation
- The code slices the string
sfrom index 2 to 4 (not including index 5). - It uses Python's string slicing feature.
- The expected output is
llo, which is the substring ofsstarting at index 2 and ending at index 4. - This operation does not modify the original string
s; it simply extracts a portion of it. - The
printfunction is used to display the sliced substring.
Output
Example 6
Explanation
- The code slices the string
sstarting from index 2 to the end. - It uses Python's string slicing feature where
s[start:]returns a substring from the start index to the end of the string. - The expected output is
'llo world', which is the part of the stringsafter the first two characters. - This operation does not modify the original string
s; it simply creates and prints a new substring. - No side effects occur as the code only performs a read operation on the string.
Output
Example 7
Explanation
- The code slices the string
swhich contains the value'hello world'. - It uses Python's slicing syntax
s[start:stop:step]wherestartis 0,stopis 6, andstepis 2. - This means it starts at the first character (index 0), goes up to but does not include the 7th character (index 6), and selects every second character in between.
- The expected output is
'hlo', as it takes characters at indices 0, 2, and 4 from the string'hello world'.
Output
Example 8
Explanation
- The code slices the string
sto exclude the last two characters. - It uses Python's slicing feature where
s[:-2]means "take the stringsfrom the beginning up to, but not including, the second-to-last character." - The key function here is the slicing operation itself, which is part of Python's string handling capabilities.
- The expected output is
'hello wor', as it prints the stringswithout the last two characters ('ld').
Output
Example 9
Explanation
- The code slices the string
sfrom index 6 to index 0, moving backwards by 1 step each time. - It uses Python's string slicing feature, where
s[start:stop:step]is the syntax. - The
startindex is 6,stopindex is 0, andstepis -1, indicating reverse slicing. - The expected output is
'dlrow', which is the substring ofsfrom 'w' to 'd' in reverse order. - No side effects; it only prints the sliced string to the console.
Output
Example 10
Explanation
- The code reverses the string stored in the variable
s. - It uses Python's slicing feature where
[::-1]indicates that the string should be traversed from the end to the beginning. - The
print()function is used to display the reversed string on the console. - Expected output is the reversed version of the string
s. - There are no side-effects; it only outputs the reversed string.
Output
Example 11
Explanation
- Prints the last five characters of the string stored in variable
s - Uses Python's slicing feature to extract a substring
- The slice
-5:indicates starting from the fifth character from the end to the end of the string - Expected output is the last five characters of the string
s - If
shas fewer than five characters, it prints the entire strings
Output
Example 12
Explanation
- The code prints a substring of the variable
sin reverse order. - It uses Python's slicing feature with the syntax
s[start:stop:step]. - The
startindex is-1, which refers to the last character of the strings. - The
stopindex is-6, indicating the position before the sixth character from the end, but since the step is negative, it includes up to the sixth character from the end. - The
stepis-1, which means the slicing goes backwards through the string. - Expected output is the last five characters of the string
sin reverse order.
Output
Editing and Deleting in String
Example 13
Explanation
- The code attempts to change the first character of the string
sfrom 'h' to 'H'. - It uses indexing
s[0]to access the first character of the string. - The assignment
s[0] = 'H'is intended to modify the string, but it will raise a TypeError because strings in Python are immutable. - The
print(s)statement is meant to display the modified string, but due to the error, it will not execute as intended. - The comment
# Python strings are immutableexplains that strings cannot be changed after they are created, which is why the assignment operation fails.
Output
Example 14
Explanation
- The code attempts to delete the string variable
swhich is initially set to'hello world'. - It uses the
delstatement to remove the variablesfrom the current namespace. - After deletion, attempting to print
swill result in aNameErrorbecausesno longer exists. - The expected side-effect is that the variable
sis removed from memory. - The expected output is an error message indicating that the name
sis not defined.
Output
Example 15
Explanation
- The code attempts to delete characters from the string
susing slicing. del s[-1:-5]is intended to remove characters from index -1 to -5, but since the start index is greater than the end index, it does nothing.- The
print(s)function outputs the original stringswithout any modifications. - Expected output is
hello worldas the deletion operation has no effect on the string. - This demonstrates how Python handles slicing with reversed indices in a deletion context.
Output
Operators on Strings
* Arithmetic Operators
* Relational Operators
* Logical Operators
* Loops on Strings
* Membership Operators
Example 16
Explanation
- The code concatenates two strings, 'Madhu' and 'Dadi', with a space in between.
- It uses the
+operator to concatenate strings. - The
print()function is used to output the concatenated string to the console. - Expected output is the string "Madhu Dadi".
- There are no side effects other than displaying the output on the console.
Output
Example 17
Explanation
- The code multiplies the string 'Madhu' by 5.
- It uses the
*operator to repeat the string. - The expected output is the string 'MadhuMadhuMadhuMadhuMadhu'.
- This operation does not have any side effects; it simply prints the result to the console.
Output
Example 18
Explanation
- Prints a string of asterisks (
*) repeated 50 times. - Uses the
print()function to output the string to the console. - The
*operator is used to repeat the string. - Expected output is a line of 50 asterisks.
- No side-effects other than displaying text on the console.
Output
Example 19
Explanation
- The code compares two strings, 'Delhi' and 'Mumbai', using the equality operator
==. - It checks if the string 'Delhi' is exactly the same as the string 'Mumbai'.
- The comparison is case-sensitive, meaning 'Delhi' and 'delhi' would be considered different.
- The expected output of this comparison is
Falsesince 'Delhi' is not equal to 'Mumbai'. - This operation does not have any side-effects; it simply returns a boolean value indicating the result of the comparison.
Output
Example 20
Explanation
- Compares the string 'Delhi' with the string 'delhi' for inequality.
- Uses the
!=operator to check if the two strings are not equal. - The comparison is case-sensitive, meaning 'Delhi' and 'delhi' are considered different.
- Returns
Truebecause the strings differ in case. - No side-effects; simply evaluates and returns a boolean value.
Output
Example 21
Explanation
- Compares the string 'Mumbai' with the string 'Pune' lexicographically.
- Uses the greater than (
>) operator to perform the comparison based on ASCII values of characters. - Returns
Falsebecause 'Mumbai' comes before 'Pune' in lexicographical order. - Demonstrates how Python compares strings character by character from left to right.
- No side effects; simply evaluates the expression and returns a boolean value.
Output
Example 22
Explanation
- Compares the string 'Pune' with the string 'Mumbai' lexicographically.
- Uses the greater than (
>) operator to determine if 'Pune' comes after 'Mumbai' in dictionary order. - Returns
Truebecause 'Pune' is lexicographically greater than 'Mumbai'. - No side effects; simply evaluates the comparison and returns a boolean value.
- Expected output is
True.
Output
Example 23
Explanation
- The code compares two strings: 'Pune' and 'pune'.
- It uses the greater than (
>) operator to compare the ASCII values of the characters in the strings. - The comparison is case-sensitive, meaning uppercase letters have lower ASCII values than lowercase letters.
- The expected output is
Falsebecause the ASCII value of 'P' (80) is less than the ASCII value of 'p' (112). - This comparison reflects the lexicographical order based on ASCII values, where 'Pune' comes before 'pune'.
Output
Example 24
Explanation
- The code performs a logical AND operation between two string literals,
'hello'and'world'. - In Python, non-empty strings are considered
Truein a boolean context. - The
andoperator returns the second operand if both operands are truthy; otherwise, it returns the first operand that is falsy. - Since both
'hello'and'world'are truthy, the expression evaluates to'world'. - This cell does not have any side effects; it simply evaluates the expression and returns the result.
Output
Example 25
Explanation
- The code evaluates an expression using the logical
oroperator between two string literals. - In Python, the
oroperator returns the first truthy value it encounters or the last value if none are truthy. - Both
'hello'and'world'are non-empty strings, which are considered truthy in Python. - Therefore, the expression evaluates to
'hello', as it is the first truthy value. - This code does not have any side effects; it simply returns a value.
Output
Example 26
Explanation
- The code evaluates an expression that uses the logical AND operator (
and) between two string literals. - The first string is an empty string (
''), which is consideredFalsein a boolean context. - The second string is
'world', which is consideredTruein a boolean context. - Since the first operand is
False, the expression short-circuits and returns the first operand without evaluating the second. - The expected output of this expression is an empty string (
'').
Output
Example 27
Explanation
- The code evaluates an expression using the
oroperator between two string literals. - The
oroperator returns the first truthy value it encounters. In Python, non-empty strings are considered truthy. - Since
'world'is not an empty string, it is evaluated as truthy. - The expression will return
'world'because it is the first truthy value in the evaluation. - There are no side effects; the code simply returns a value.
Output
Example 28
Explanation
- The code evaluates the logical NOT of the string
'hello' - In Python, non-empty strings are considered
Truein a boolean context - The
notoperator negates the boolean value, so it returnsFalse - There are no key functions or APIs used in this simple expression
- The expected output is
False
Output
Example 29
Explanation
- Evaluates whether the empty string is considered
Falsein a boolean context - Uses the
notoperator to invert the truth value of the empty string - The empty string
''is inherentlyFalsein Python - The result of
not ''isTrue - No side effects; simply returns a boolean value
Output
Example 30
Explanation
- Iterates over each character in the string 'hello'
- Uses the
forloop to go through each element in the iterable (string in this case) - The variable
itakes on the value of each character in the string during each iteration - Calls the
print()function to output each character on a new line - Expected output is each letter of 'hello' printed individually: h e l l o
Output
Example 31
Explanation
- The code iterates over each character in the string 'delhi'.
- For each character in the string, it prints the word 'pune'.
- Key function used is
print(), which outputs text to the console. - Expected output is the word 'pune' printed five times, once for each character in 'delhi'.
- There are no side effects other than the console output.
Output
Example 32
Explanation
- The code checks if the character
'd'is present in the string'delhi'. - It uses the
inoperator, which is a membership operator in Python. - The expected output is
True, as'd'is indeed a member of the string'delhi'.
Output
Example 33
Explanation
- The code checks if the character
'd'is not present in the string'Delhi'. - It uses the
not inoperator to perform the membership test. - The expected output is a boolean value,
True, because'd'(lowercase) is not found in'Delhi'(which contains'D'uppercase). - This operation is case-sensitive, meaning it distinguishes between uppercase and lowercase letters.
- There are no side-effects; the code simply evaluates and returns a boolean result.
Output
Common Functions
* len
* max
* min
* sorted
Example 34
Explanation
- The code calculates the length of the string 'hello world'.
- It uses the built-in
len()function to determine the number of characters in the string. - The expected output is an integer representing the total number of characters, which is 11 in this case.
- This code does not have any side effects; it simply returns the length of the string.
- The space between 'hello' and 'world' is counted as one character in the length calculation.
Output
Example 35
Explanation
- The code finds the maximum character in the string 'hello world' based on ASCII values.
- It uses the built-in
max()function to determine the highest ASCII value among the characters in the string. - The expected output is the character 'w', which has the highest ASCII value in the given string.
- This operation does not have any side effects; it simply returns the result of the comparison.
- The function compares each character's ASCII value, where 'w' (ASCII 119) is greater than all other characters in the string.
Output
Example 36
Explanation
- The code finds the minimum character in the string 'hello world' based on ASCII values.
- It uses the built-in
min()function which returns the smallest item in an iterable. - The expected output is the character ' ' (space), as it has the lowest ASCII value among all characters in the string.
- This operation does not have any side effects; it simply returns a value.
- The comparison is case-sensitive, meaning uppercase letters would be considered smaller than lowercase letters if present.
Output
Example 37
Explanation
- The code sorts the characters in the string 'hello world'.
- Uses the built-in
sorted()function which returns a new list containing all items from the iterable in ascending order. - Sorting is based on ASCII values, so spaces come before letters.
- Expected output is a list of characters: [' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w'].
- No side-effects; the original string remains unchanged.
Output
Capitalize / Title / Upper / Lower / Swapcase
Example 38
Explanation
- The code assigns the string
'hello world'to the variables. - It then calls the
capitalize()method on the strings. - The
capitalize()method converts the first character of the string to uppercase and the rest to lowercase. - This operation does not modify the original string
sbut returns a new capitalized string. - The expected output is
'Hello world', which is not stored or printed in this code snippet.
Output
Example 39
Explanation
- Converts the string
sto title case, capitalizing the first letter of each word. - Uses the
title()method, which is a built-in string method in Python. - Expected output is a new string where the first character of each word is uppercase and the rest are lowercase.
- Does not modify the original string
s; instead, it returns a new string with the title case transformation. - Side-effect is none, as strings in Python are immutable and the method does not alter the input string directly.
Output
Example 40
Explanation
- Converts all lowercase letters in the string
sto uppercase. - Uses the
upper()method, which is a built-in string method in Python. - Does not modify the original string
s; instead, it returns a new string with all characters in uppercase. - Expected output is a string where all alphabetic characters are converted to their uppercase equivalents.
- If
scontains no lowercase letters, the returned string will be identical tos.
Output
Example 41
Explanation
- Converts all uppercase characters in the string
sto lowercase. - Uses the
lower()method, which is a built-in string method in Python. - Does not modify the original string
s; instead, it returns a new string with all characters in lowercase. - Expected output is a string where all alphabetic characters are in lowercase.
- No side-effects; the original string remains unchanged.
Output
Example 42
Explanation
- Converts all uppercase letters to lowercase and vice versa in the string 'HeLlO WorLD'
- Uses the
swapcase()method which is a built-in string function in Python - Expected output is the string 'hElLo wORld'
- No side-effects as strings in Python are immutable and the method returns a new string
- Demonstrates string manipulation and case conversion in Python
Output
Count / Find / Index
Example 43
Explanation
- The code counts the number of times the character 'i' appears in the string 'my name is madhu'.
- It uses the
count()method, which is a built-in string method in Python. - The expected output is an integer representing the count of 'i' in the string.
- In this case, the output will be
1because 'i' appears once in the string. - There are no side-effects; the method simply returns a value without modifying the original string.
Output
Example 44
Explanation
- The code counts the number of times the character 'm' appears in the string 'my name is madhu'.
- It uses the
count()method, which is a built-in string method in Python. - The expected output is an integer representing the count of 'm', which is 2 in this case.
- This method is case-sensitive, so it only counts lowercase 'm'.
- There are no side-effects; it simply returns the count without modifying the original string.
Output
Example 45
Explanation
- The code searches for the substring 'madhu' within the string 'my name is madhu'.
- It uses the
find()method, which returns the lowest index of the substring if it is found. - If the substring is not found, the
find()method would return -1. - In this case, since 'madhu' is present, the expected output is the index 7, where 'madhu' starts in the string.
- This operation does not modify the original string; it simply returns an integer value indicating the position.
Output
Example 46
Explanation
- The code searches for the substring 'is' within the string 'my name is madhu'.
- It uses the
findmethod, which returns the lowest index of the substring if it is found. - If the substring is not found, the
findmethod would return -1, but in this case, 'is' is present. - The expected output is
5, as 'is' starts at the 5th index of the string (considering 0-based indexing). - This operation does not have any side effects; it simply returns an integer value.
Output
Example 47
Explanation
- The code searches for the substring
'x'within the string'my name is madhu'. - It uses the
find()method, which returns the lowest index of the substring if it is found. - If the substring is not found, as in this case,
find()returns-1. - The expected output is
-1since'x'does not exist in the string'my name is madhu'. - There are no side effects; the method simply returns an integer value.
Output
Example 48
Explanation
- The code finds the starting index of the substring 'is' within the string 'my name is madhu'.
- It uses the
index()method, which searches for the first occurrence of the specified value and returns its position. - The expected output is the integer
7, as 'is' starts at the 7th index of the string (considering the first character is at index 0). - If the substring is not found, the
index()method would raise aValueError. - This operation does not modify the original string; it simply returns the index position.
Output
Example 49
Explanation
- The code attempts to find the index of the substring
'x'within the string'my name is madhu'. - It uses the
index()method, which searches for the first occurrence of the specified value and returns its position. - If the substring is not found, the
index()method raises aValueError. - In this case, since
'x'is not present in the string, aValueErrorwill be raised. - The comment indicates that the difference between
find()andindex()is thatfind()returns-1if the substring is not found, whereasindex()raises an error.
Output
endswith / startswith
Example 50
Explanation
- The code checks if the string
'my name is madhu'ends with the substring'madhu'. - It uses the
endswith()method, which is a string method in Python. - The method returns
Trueif the string ends with the specified suffix, otherwise it returnsFalse. - In this case, the expected output is
Truebecause the string does indeed end with'madhu'. - There are no side-effects; the method simply returns a boolean value.
Output
Example 51
Explanation
- The code checks if the string
'my name is madhu'ends with the substring'aa'. - It uses the
endswith()method, which is a built-in string method in Python. - The method returns a boolean value:
Trueif the string ends with the specified suffix, otherwiseFalse. - In this case, the expected output is
Falsebecause the string does not end with'aa'. - This operation does not have any side effects; it simply evaluates and returns the result.
Output
Example 52
Explanation
- The code checks if the string
'my name is madhu'begins with the character'm'. - It uses the
startswith()method, which is a string method in Python. - The method returns a boolean value:
Trueif the string starts with the specified prefix, otherwiseFalse. - In this case, the expected output is
Truebecause the string does indeed start with'm'. - There are no side effects; the method simply evaluates and returns a boolean.
Output
Example 53
Explanation
- The code checks if the string
'my name is madhu'starts with the substring'madhu'. - It uses the
startswith()method, which is a string method in Python. - The method returns
Falsebecause the string does not start with'madhu'; it starts with'my'. - No side effects; it simply evaluates and returns a boolean value.
- Expected output is
False.
Output
Format
Example 54
Explanation
- The code creates two variables,
nameandgender, with the values'madhu'and'male', respectively. - It uses the
format()method of string objects to insert the values ofnameandgenderinto the placeholders{}within the string. - The
format()method replaces the first placeholder{}with the value ofnameand the second placeholder{}with the value ofgender. - The expected output is the string
'Hi my name is madhu and I am a male'.
Output
Example 55
Explanation
- The code creates two string variables,
nameandgender, with values'madhu'and'male'respectively. - It uses the
format()method of strings to insert the values ofgenderandnameinto a template string. - The placeholders
{1}and{0}in the template string refer to the second and first arguments passed to theformat()method, respectively. - The expected output of this code is the string
'Hi my name is madhu and I am a male'. - This code does not have any side effects; it simply returns a formatted string.
Output
isalnum / isalpha / isdigit / isidentifier
Example 56
Explanation
- The code checks if the string
'madhu245'consists only of alphanumeric characters (letters and numbers). - It uses the
isalnum()method, which is a built-in string method in Python. - The method returns
Trueif all characters in the string are alphanumeric and there is at least one character, otherwise it returnsFalse. - In this case, since
'madhu245'contains only letters and numbers, the expected output isTrue. - The comment
# Alphanumericindicates that the string being checked is expected to be alphanumeric.
Output
Example 57
Explanation
- The code checks if the string
'madhu245%'consists only of alphanumeric characters. - It uses the
isalnum()method, which returnsTrueif all characters in the string are alphanumeric and there is at least one character, otherwise it returnsFalse. - The string contains non-alphanumeric characters (
'%'), so the expected output isFalse.
Output
Example 58
Explanation
- Checks if all characters in the string 'madhu245' are alphabetic.
- Uses the
isalpha()method, which returnsTrueif all characters in the string are alphabetic and there is at least one character, otherwise it returnsFalse. - Expected output is
Falsebecause the string contains numeric characters ('2', '4', '5').
Output
Example 59
Explanation
- The code checks if all characters in the string
'madhu'are alphabetic. - It uses the
isalpha()method, which returnsTrueif all characters in the string are alphabetic and there is at least one character, otherwise it returnsFalse. - Expected output is
Truebecause the string'madhu'contains only alphabetic characters. - This method is useful for validating input where only letters are allowed.
- The comment
# Alphabets onlyindicates the purpose of the check.
Output
Example 60
Explanation
- Checks if the string
'madhu245'consists solely of digit characters. - Uses the
isdigit()method, which returnsTrueif all characters in the string are digits and there is at least one character, otherwise returnsFalse. - Expected output is
Falsebecause the string contains non-digit characters ('m', 'a', 'd', 'h', 'u'). - No side-effects; it simply evaluates and returns a boolean value.
Output
Example 61
Explanation
- The code checks if the string
'123'consists solely of digit characters. - It uses the
isdigit()method, which is a built-in string method in Python. - The method returns
Trueif all characters in the string are digits and there is at least one character, otherwise it returnsFalse. - In this case, since
'123'contains only digits, the expected output isTrue. - There are no side effects; the method simply evaluates and returns a boolean value.
Output
Example 62
Explanation
- Checks if the string
'1name'is a valid Python identifier. - Uses the
isidentifier()method of the string class. - Returns
Falsebecause identifiers cannot start with a digit in Python. - Expected output is a boolean value indicating the validity of the string as an identifier.
- No side effects; simply evaluates and returns the result.
Output
Example 63
Explanation
- Checks if the string
'name1'is a valid Python identifier. - Uses the
isidentifier()method which returnsTrueif the string is a valid identifier according to Python's language definition. - A valid identifier must start with a letter or underscore, followed by any number of letters, digits, or underscores.
- Expected output is
Truesince'name1'starts with a letter and contains only letters and digits. - No side effects, simply returns a boolean value.
Output
Example 64
Explanation
- Checks if the string 'first_name' is a valid Python identifier
- Uses the
isidentifier()method of string objects - Returns
Trueif 'first_name' is a valid identifier, otherwiseFalse - In this case, it will return
Truebecause 'first_name' follows Python's rules for identifiers (starts with a letter or underscore, followed by any number of letters, digits, or underscores)
Output
Example 65
Explanation
- Checks if the string 'first-name' is a valid Python identifier.
- Uses the
isidentifier()method of string objects. - Returns
Falsebecause hyphens are not allowed in Python identifiers. - Expected output is a boolean value indicating validity as an identifier.
- No side-effects; simply evaluates and returns a result.
Output
Split / Join
Example 66
Explanation
- The code splits the string
'hi my name is madhu'into a list of words. - It uses the
split()method, which by default splits the string at any whitespace. - The expected output is a list containing the words
['hi', 'my', 'name', 'is', 'madhu']. - There are no side effects; it simply returns a new list without modifying the original string.
Output
Example 67
Explanation
- The code splits the string
'hi my name is madhu'into a list of substrings. - It uses the
split()method, which divides the string at each occurrence of the specified separator,'i'in this case. - The expected output is a list containing the substrings
['h', ' my name s m', 'du']. - This operation does not modify the original string but returns a new list.
- The
split()method is useful for breaking down strings into components based on a delimiter.
Output
Example 68
Explanation
- Joins a list of strings into a single string with spaces between each element
- Uses the
join()method of a string object, which concatenates the elements of an iterable (in this case, a list) into a single string - The iterable contains the words 'hi', 'my', 'name', 'is', 'madhu'
- Expected output is the string "hi my name is madhu"
- No side-effects; simply returns the concatenated string
Output
Example 69
Explanation
- The code concatenates a list of strings into a single string.
- It uses the
join()method of a string object, which takes an iterable (in this case, a list) and joins its elements separated by the string on whichjoin()is called. - The string
'-'is used as a separator between each element of the list. - The expected output is the string
'hi-my-name-is-madhu'. - There are no side effects; the function returns a new string and does not modify the original list.
Output
Replace
Example 70
Explanation
- The code replaces the substring 'madhu' with 'dadi' in the string 'hi my name is madhu'.
- Key function used is
replace(), which is a string method in Python. - Expected output is the string 'hi my name is dadi'.
- There are no side-effects as strings in Python are immutable, meaning the original string remains unchanged.
- The
replace()function returns a new string with the specified replacements.
Output
Example 71
Explanation
- The code attempts to replace occurrences of the substring 'aaaa' with 'dadi' in the string 'hi my name is madhu'.
- The
replacefunction is used here, which is a string method in Python. - Since 'aaaa' does not exist in the original string, the string remains unchanged.
- The expected output of this code is 'hi my name is madhu'.
- There are no side-effects; the operation does not modify any external variables or state.
Output
Strip
Example 72
Explanation
- The code removes any leading and trailing whitespace characters from the string
'Madhu '. - It uses the
strip()method, which is a built-in string function in Python. - The expected output is the string
'Madhu'without any trailing spaces. - There are no side-effects; the original string remains unchanged as strings are immutable in Python.
- The result of this operation would typically be assigned to a variable or used directly in further operations.
Output
Example 73
Explanation
- The code removes leading and trailing hyphens from the string 'Madhu----------'.
- It uses the
strip()method of Python strings, which is designed to remove specified characters from the beginning and end of a string. - The argument
'-'passed tostrip()indicates that hyphens should be removed. - The expected output is the string 'Madhu' without any leading or trailing hyphens.
- There are no side-effects; the operation returns a new string and does not modify the original string.
Output
Example Programs
Example 74
Explanation
- The code prompts the user to enter a string.
- It initializes a variable
counterto zero, which will be used to count the number of characters in the string. - A
forloop iterates over each character in the strings, incrementing thecounterby one for each character. - After the loop completes, the code prints the total count of characters in the string, which represents the length of the string.
- The expected output is a message displaying the length of the string entered by the user.
Output
Example 75
Explanation
- The code prompts the user to enter an email address.
- It uses the
findmethod to locate the position of the '@' symbol in the email string. - The code then slices the string from the beginning up to (but not including) the '@' symbol's position.
- This sliced string, which represents the username part of the email, is printed to the console.
- If the '@' symbol is not found, the
findmethod returns -1, and the entire input string is printed as the username.
Output
Example 76
Explanation
- Prompts the user to enter a string and stores it in the variable
s - Asks the user for a specific character to search for within the string and stores it in the variable
term - Initializes a counter variable to zero, which will keep track of how many times
termappears ins - Iterates through each character in the string
s, checking if it matchesterm; if it does, increments the counter by one - Outputs the total frequency of the character
termfound in the strings
Output
Example 77
Explanation
- Prompts the user to enter a string and stores it in the variable
s - Asks the user for a specific term to search within the string and stores it in the variable
term - Uses the
countmethod of the string objectsto find how many timestermappears ins - Prints out the frequency of the term in the format "frequency is X", where X is the count
- Expects the user to input a string and a term, and outputs the number of occurrences of the term in the string
Output
Example 78
Explanation
- The code prompts the user to enter a string and a character they wish to remove from that string.
- It initializes an empty string
resultto accumulate characters that are not the one to be removed. - The code iterates over each character
iin the input strings. - If the current character
iis not equal to the character specified interm, it appendsitoresult. - Finally, the code prints the modified string
resultwhich has all instances of the specified character removed.
Output
Example 79
Explanation
- The code prompts the user to enter a string.
- It checks if the string is equal to its reverse (
s[::-1]). - If the string is the same forwards and backwards, it prints 'Palendrome'.
- If the string is not the same forwards and backwards, it prints 'Not Palendrome'.
- The expected output is either 'Palendrome' or 'Not Palendrome', depending on the user's input.
Output
Example 80
Explanation
- The program checks if the input string is a palindrome by comparing characters from the beginning and end moving towards the center.
input('Enter a string:')is used to take a string input from the user.- The
forloop iterates over the first half of the string, comparing each character with its corresponding character from the end. - If any pair of characters doesn't match,
flagis set toFalseand the loop breaks, indicating the string is not a palindrome. - Depending on the value of
flag, the program prints 'Palendrome' if all characters matched correctly, otherwise it prints 'Not Palendrome'. Note: There is a typo in the word 'Palindrome'.
Output
Example 81
Explanation
- The code prompts the user to enter a string.
- It initializes an empty list
Lto store words and a temporary stringtempto build each word. - It iterates over each character
iin the input strings. - If the character is not a space, it adds the character to
temp; otherwise, it appendstempto the listLand resetstempto an empty string. - After the loop, it appends the last
temptoLto ensure the final word is included, then prints the listLcontaining all the words from the input string.
Output
Example 82
Explanation
- The code takes a string input from the user.
- It splits the string into words using the
split()method. - For each word, it capitalizes the first letter using
upper()and makes the rest of the letters lowercase usinglower(), then appends the modified word to listL. - It prints the list
Lcontaining the words in title case. - It joins the list
Linto a single string with spaces between words usingjoin()and prints the resulting title-cased string.
Output
Example 83
Explanation
- The code converts an integer input by the user into its string representation.
- It uses the
input()function to take user input andint()to convert it to an integer. - The
whileloop continues until the number is reduced to zero, extracting each digit by using the modulus operator%and integer division//. - Inside the loop, it prepends the corresponding character from the
digitsstring to theresultstring based on the current least significant digit ofnumber. - Finally, it prints the
result, which is the string representation of the original integer.
Output
Problem 1 - Print the following pattern. Write a program to use for loop to print the following reverse number pattern.
Example 84
Explanation
- Prompts the user to enter the number of rows for a pattern.
- Uses nested loops to print numbers in descending order for each row.
- The outer loop iterates over the range from 0 to the number of rows specified by the user.
- The inner loop counts down from the current row number to 1, printing each number followed by a space.
- Prints a new line after completing each row's number sequence, resulting in a right-angled triangle pattern of numbers.
Output
Problem 2: Print the following pattern.
Example 85
Explanation
- The code prompts the user to enter the number of rows for a pattern.
- It uses nested
forloops to print a pyramid pattern of asterisks (*) based on the input number of rows. - The first loop constructs the upper half of the pyramid by printing increasing numbers of asterisks on each line.
- The second loop constructs the lower half of the pyramid by printing decreasing numbers of asterisks on each line.
- The
print('*', end=' ')statement prints an asterisk followed by a space without moving to a new line, allowing multiple asterisks to be printed on the same line. - The
print()statement after the inner loops moves the cursor to the next line after printing each row of asterisks.
Output
Problem 3:Write a program to pring the following pattern
Example 86
Explanation
- The code prints a right-aligned pattern of asterisks (
*) forming a triangle. - It uses the
rangefunction to iterate from 1 torows(inclusive), whererowsis initially set to 6. - The
printfunction is used twice in each iteration: first to print spaces for alignment, and second to print the asterisks. - The
end=''parameter in the firstprintcall prevents moving to a new line after printing spaces. - In each iteration, the number of spaces decreases by 1 and the number of asterisks increases by 1, creating a right-aligned triangular pattern of asterisks.
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
Example 87
Explanation
- The code prints a pattern of numbers in descending order for each row, starting from 1 up to the specified number of rows.
- It uses the
range()function to generate sequences of numbers for both the outer and inner loops. - The outer loop iterates over the range from 1 to
rows + 1, controlling the number of rows. - The inner loop iterates backward from the current row number
idown to 1, printing each number followed by a space on the same line. - Each row ends with a newline character, resulting in a pyramid-like pattern of numbers printed to the console.
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
Example 88
Explanation
- Initializes variables
xandnwith values 10 and 5 respectively. - Uses a loop to calculate the sum of the series
1 + x^2/2 + x^3/3 + ... + x^n/n. - Constructs a string
sthat represents the series in a readable format. - Prints the series without the trailing '+' symbol.
- Outputs the calculated sum of the series.
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.
Example 89
Explanation
- The code calculates a partial sum of a series where each term is
(1/i) * ((x-1)/x)^iforiranging from 1 ton. - It uses the
range()function to iterate from 1 toninclusive. - The
format()method is used to construct a stringsthat represents the series in a readable format. - The final string
shas a trailing+which is removed before printing usings[:-1]. - The code prints the constructed series string without the last
+and the calculated 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:
Example 90
Explanation
- Prompts the user to enter the number of terms they want in the sequence.
- Initializes
startto 2 andsumto 0 to begin the sequence and keep track of the total sum. - Iterates
ntimes, printing each term of the sequence followed by a '+' except for the last term. - In each iteration, adds the current
startvalue tosum. - Updates
startto the next term in the sequence by multiplying it by 10 and adding 2. - After the loop, prints the final sum of the sequence.
Output
###Problem 8: Write a program to print all the unique combinations of 1,2,3 and 4
Output:
Example 91
Explanation
- The code uses nested loops to iterate over four ranges, each from 1 to 4.
- It prints out all possible combinations of four numbers, where each number is between 1 and 4 inclusive.
- The
range(1,5)function generates numbers starting from 1 up to, but not including, 5. - The
print(i,j,k,m)statement outputs the current values ofi,j,k, andmon each iteration. - The expected output is a list of 256 tuples, each representing a unique combination of four numbers from 1 to 4.
Output
###Problem 9: Write a program that will take a decimal number as input and prints out the binary equivalent of the number
Example 92
Explanation
- Prompts the user to enter a number and converts it to an integer.
- Initializes an empty list named
binaryto store binary digits. - Uses a while loop to repeatedly divide the number by 2, appending the remainder to the
binarylist until the number becomes 0. - Prints the current value of
nand the updatedbinarylist after each division. - Iterates over the
binarylist in reverse order, printing each element without a newline, to display the binary representation of the entered number.
Output
###Problem 10: Write a program that will take 2 numbers as input and prints the LCM and HCF of those 2 numbers
Example 93
Explanation
- The code prompts the user to enter two numbers.
- It calculates the Least Common Multiple (LCM) of the two numbers using a while loop that increments the greater of the two numbers until it finds a number divisible by both.
- It calculates the Highest Common Factor (HCF), also known as the Greatest Common Divisor (GCD), of the two numbers using a for loop that checks each number from 1 to the smaller of the two numbers to see if it divides both without a remainder.
- The LCM and HCF of the entered numbers are printed to the console.
- The code uses
input()to get user input,int()to convert the input to integers, and basic arithmetic operations like modulus (%) to determine divisibility.
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:
Example 94
Explanation
- The code takes a string
inpcontaining "Data science mentorship program". - It initializes an empty string
resto accumulate results. - It splits the input string into words using
split()method. - For each word, it converts the first character to uppercase using
i[0].upper()and appends it tores. - Finally, it prints
res, which will be "Dsmp" - the first letter of each word in uppercase.
Output
###Problem 12: Append second string in the middle of first string
Input:
Output:
Example 95
Explanation
- Prompts the user to enter two strings, storing them in variables
s1ands2. - Calculates the midpoint of
s1using integer division of its length by 2. - Concatenates the first half of
s1, the entires2, and the second half ofs1. - Prints the resulting concatenated string to the console.
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
Example 96
Explanation
- The code iterates through each character in the string
s. - It checks if the character is lowercase using the
islower()method. - If the character is lowercase, it appends it to the
lowerstring; otherwise, it appends it to theupperstring. - Finally, it prints the concatenation of
lowerandupper, which results in all lowercase letters ofsfollowed by all uppercase letters. - Expected output for the given string
sisyaivePNt.
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:
Example 97
Explanation
- The code iterates through each character in the string
s. - It checks if the character is a digit using the
isdigit()method. - If the character is a digit, it converts the character to an integer with
int(i)and adds it tosum, while also incrementingcountby 1. - After the loop, it prints the total sum of all digits found in the string.
- It then prints the average of these digits by dividing
sumbycount.
Output
Problem 15: Removal of all characters from a string except integers
Given:
Expected Output:
Example 98
Explanation
- The code iterates over each character in the string
s. - It checks if the character is a digit using the
isdigit()method. - If the character is a digit, it appends it to the result string
res. - After the loop,
rescontains all the digits found in the original string concatenated together. - The
print(res)statement outputs the concatenated digits, which in this case would be2510.
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
Example 99
Explanation
- The code prompts the user to enter a string.
- It checks if the length of the string is even or odd.
- If even, it splits the string into two halves; if odd, it splits the string into two halves excluding the middle character.
- It compares the two halves of the string.
- Prints 'Symmetric' if both halves are identical, otherwise prints 'Not Symmetric'.
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:
Example 100
Explanation
- The code takes a string
scontaining "My name is Madhu Dadi". - It splits the string into a list of words using the
split()method, resulting in['My', 'name', 'is', 'Madhu', 'Dadi']. - Each word is appended to an initially empty list
L. - The list
Lis reversed using slicing[::-1], changing it to['Dadi', 'Madhu', 'is', 'name', 'My']. - The reversed list is joined back into a string with spaces between words using
" ".join(L), and printed, resulting in "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:
Example 101
Explanation
- The code initializes two strings,
AandB, containing space-separated words. - It creates an empty list
Lto store unique words that are not common betweenAandB. - The first loop iterates over each word in string
A. If a word is not found in stringBand also not already in listL, it appends the word toL. - The second loop iterates over each word in string
B. Similarly, if a word is not found in stringAand not in listL, it appends the word toL. - Finally, the code prints the list
L, which contains words unique to either or . Expected output for given and is .
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
Example 102
Explanation
- The code splits the string
sinto words and iterates over each word. - It keeps track of the position of each word using the variable
pos. - If the current word matches the target word
Madhu, the loop breaks. - The final value of
posis printed, which represents the position of the wordMadhuin the strings. - Expected output is
6, asMadhuis the 6th word in the string.
Output
Problem 20: Write a program that can remove all the duplicate characters from a string. User will provide the input.
Example 103
Explanation
- The code iterates over each character in the string
s. - It checks if the character is not already present in the result string
res. - If the character is unique so far, it appends the character to
res. - After the loop,
rescontains all unique characters fromsin the order they first appeared. - The
print(res)statement outputs the string'abcdef', which consists of the unique characters from the original string.
Output

