Python String

Python String Tutorials

Introduction:

A string is a sequence of characters. In Python, you can define a string using either single quotes () or double quotes (), or triple quotes (”’ or “””) for multiline strings. Here are some examples:

# Defining strings in Python

# Single-quoted string
single_quote_str = 'Hello, World!'
print("Single-quoted string:", single_quote_str)

# Double-quoted string
double_quote_str = "Hello, Python!"
print("Double-quoted string:", double_quote_str)

# Triple-quoted string (for multiline text)
triple_quote_str = '''This is a
multiline string.
It spans multiple lines.'''
print("Triple-quoted string:")
print(triple_quote_str)

Python string features:

  1. Immutable: Strings in Python are immutable, meaning that once a string is created, its contents cannot be changed. If you want to modify a string, you need to create a new string with the desired changes.
  2. Sequence of Characters: Strings are a sequence of individual characters. Each character in a string is assigned an index, starting from 0 for the first character. This allows you to access and manipulate specific characters within a string using indexing and slicing operations.
  3. Unicode Support: Python strings support Unicode, allowing you to work with characters from different languages, including non-ASCII characters. This enables you to handle and process text in various encodings and writing systems.
  4. Concatenation: Strings can be concatenated using the “+” operator, allowing you to combine multiple strings into a single string. For example, “Hello” + ” ” + “World” results in the string “Hello World”.
  5. Length: You can obtain the length of a string using the `len()` function, which returns the number of characters in the string. This is useful for determining the size of a string or iterating over its characters.
  6. String Formatting: Python provides various methods for formatting strings. This includes the use of placeholders or format specifiers, such as `%` operator or the `format()` method, to insert variables or values into a string with specified formatting.
  7. String Operations and Methods: Python offers a wide range of built-in operations and methods specifically designed for working with strings. These include operations like string concatenation, repetition, and membership checks, as well as methods for case conversion, substring searching, replacing, splitting, stripping, and more.
  8. Escape Sequences: Strings in Python support escape sequences, which allow you to include special characters that are difficult to type directly. For example, using `n` represents a newline character, `t` represents a tab character, and `”` represents a double quote character within a string.
  9. String Comparison: Strings can be compared using operators such as `==`, `!=`, `<`, `>`, `<=`, and `>=`. Comparison is performed based on lexicographic (dictionary) ordering of characters, which compares each corresponding character’s Unicode value.
  10. String Iteration: Python allows you to iterate over a string using loops, enabling you to process each character individually or perform operations on the entire string.

Python string advantages:

  1. Versatility: Python strings are versatile and widely used for handling and manipulating text-based data. They can store and process alphanumeric characters, symbols, and even Unicode characters, making them suitable for various applications and internationalization needs.
  2. Immutable Nature: Python strings are immutable, meaning their contents cannot be changed once they are created. This immutability ensures the integrity of strings and prevents accidental modifications, making them reliable for operations like string matching, hashing, or as keys in dictionaries.
  3. Extensive String Methods: Python provides a rich set of built-in string methods that offer a wide range of operations. These methods allow you to perform tasks like searching, replacing, splitting, joining, formatting, case conversion, and more. The extensive set of string methods simplifies complex string manipulation tasks and saves you time and effort.
  4. Unicode Support: Python strings have excellent support for Unicode, making them capable of representing characters from various writing systems, including non-ASCII characters. This allows you to work with and process text in different languages and encodings, making Python strings suitable for internationalization and multilingual applications.
  5. String Formatting: Python offers flexible and powerful string formatting capabilities. With techniques like the `%` operator or the `format()` method, you can easily insert variables or values into a string with specified formatting. This makes it convenient for generating dynamic strings, constructing messages, or formatting output.
  6. String Interpolation: Python 3.6 and later versions introduce f-strings, which provide a concise and readable way to embed expressions within string literals. This feature, known as string interpolation, simplifies the process of combining variables and expressions with strings, improving code readability and reducing the need for concatenation.
  7. Compatibility with File Operations: Python strings integrate seamlessly with file handling operations. You can read or write strings to files, manipulate file paths as strings, and use string methods to parse or manipulate file content. This compatibility makes it easier to work with text files and perform file-related operations.
  8. Regular Expressions: Python’s `re` module offers support for regular expressions, providing powerful pattern matching and text manipulation capabilities. Regular expressions allow you to search for specific patterns, extract information, or perform complex text transformations, making them valuable for tasks like data validation, parsing, and text processing.
  9. Consistency and Familiarity: Python strings follow consistent syntax and behavior across different operations and methods. This consistency, combined with Python’s focus on readability and simplicity, makes working with strings in Python intuitive and easy for developers who are familiar with the language.
  10. Extensive Community and Documentation: Python is a widely adopted programming language, and as a result, there is a vast community of developers and extensive documentation available for working with strings. You can find libraries, tutorials, and resources to help with advanced string manipulation, handling special cases, or optimizing string-related operations.

Python string disadvantages:

  1. Immutability: While immutability can be an advantage in terms of data integrity, it can also be a disadvantage when it comes to efficiency. Since strings are immutable, any operation that involves modifying a string, such as concatenation or replacing characters, requires creating a new string object. This can be inefficient, especially when dealing with large strings or performing many operations.
  2. Memory Overhead: Each individual character in a Python string requires memory to store its Unicode value and other metadata. This fixed overhead per character can consume significant memory, especially when working with large strings or processing large amounts of text data. In scenarios with memory constraints, this overhead can become a limiting factor.
  3. Difficulty with Mutable Operations: Some string manipulation tasks, such as inserting or removing characters at specific positions, can be cumbersome and inefficient due to the immutability of strings. Achieving such operations often requires creating new string objects or converting the string to a mutable data structure like a list, performing the operation, and then converting it back to a string.
  4. Comparison Complexity: Comparing strings for equality or sorting them can have time complexity proportional to the length of the strings being compared. In cases where string comparison or sorting is a critical performance factor, more efficient data structures or algorithms, like tries or radix sort, might be more suitable.
  5. Limited Unicode Support in Older Versions: While Python has excellent Unicode support, there were limitations in earlier versions (pre-Python 3) regarding Unicode handling. Older versions required explicit encoding and decoding operations when working with non-ASCII characters, which could be a source of confusion or errors.
  6. Limited Mutable String Options: While Python strings are immutable, there may be scenarios where mutable string operations are desired. Python’s built-in string methods offer limited options for in-place modification, and workarounds like converting the string to a list and back can introduce additional complexity and potential performance drawbacks.
  7. Difficulty with Low-Level Operations: Python strings abstract away low-level memory access and manipulation, which can be advantageous for most applications. However, in certain scenarios where direct byte-level or bit-level manipulation is required, Python strings may not be the most suitable data structure, and using other byte-oriented data types or libraries may be more appropriate.
  8. Performance in Heavy String Manipulation: For scenarios that involve heavy string manipulation, such as text parsing or processing large volumes of text data, Python strings may not offer the best performance. In such cases, lower-level languages or specialized text processing libraries may provide more efficient options.

Re-assign Strings:

In Python, you can reassign a string to a new value by simply assigning the new value to the variable that holds the string.  Here’s an example:

# Initial string assignment
my_string = "Hello, World!"
print("Original string:", my_string)

# Reassigning the string to a new value
my_string = "Welcome to Python!"
print("Reassigned string:", my_string)

In the example above, the first print statement outputs “Hello, World!” because my_string is initially assigned that value. Then, my_string is reassigned to “Sqatools” and the second print statement outputs the new value.

It’s important to note that strings are immutable in Python, which means that once you create a string, you cannot modify it. When you “modify” a string by, for example, concatenating two strings or removing a character, you are actually creating a new string object. Here are some examples:

# Example to demonstrate string immutability in Python

# 1. String Concatenation
greeting = "Hello"
new_greeting = greeting + ", World!"
print("Original string (after concatenation):", greeting)  # Output: Hello
print("New string (concatenation result):", new_greeting)  # Output: Hello, World!

# 2. String Replacement
my_string = "Hello, Python!"
new_string = my_string.replace("Python", "World")
print("\nOriginal string (after replacement):", my_string)  # Output: Hello, Python!
print("New string (replacement result):", new_string)       # Output: Hello, World!

# 3. String Slicing
text = "Immutable"
sliced_text = text[:3]  # Taking the first three characters
print("\nOriginal string (after slicing):", text)           # Output: Immutable
print("Sliced string (slicing result):", sliced_text)       # Output: Imm

Deleting string:

In Python, you cannot delete individual characters in a string because strings are immutable. However, you can delete the entire string object from memory using the del statement.  Here’s an example:





In the example above, the first print statement outputs the value of my_string, which is “Hello, World!”. Then, the del statement deletes the my_string object from memory. When we try to print my_string again, we get a NameError because the variable no longer exists.

String formatting methods:

Python provides several methods for formatting strings. Here are the most commonly used methods:

  1. The % operator: This operator allows you to format strings using placeholders, which are replaced with values at runtime. Here’s an example:
# Using the % operator for string formatting
name = "Alice"
age = 25

formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, %s and %d are placeholders for the name and age variables, respectively. The values of these variables are provided in a tuple that follows the % operator.

  1. The str.format() method: This method allows you to format strings using placeholders that are enclosed in curly braces. Here’s an example:
# Using the str.format() method for string formatting
name = "Alice"
age = 25

formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, {} is a placeholder for the name and age variables. The values of these variables are provided as arguments to the str.format() method.

  1. F-strings: It allows you to embed expressions inside placeholders that are enclosed in curly braces preceded by the f character. Here’s an example:
# Using f-strings for string formatting
name = "Alice"
age = 25

# Embedding variables directly into the string
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, the f character before the string indicates that it is an f-string. The expressions inside the curly braces are evaluated at runtime and the resulting values are inserted into the string.

String operator:

In Python, strings support several operators that can be used to perform various operations on strings. Here are some of the most commonly used string operators:

  1. Concatenation (+): The + operator can be used to concatenate two or more strings. Here’s an example:
# Using the + operator to concatenate strings
str1 = "Hello"
str2 = "World"
combined_str = str1 + " " + str2  # Adding a space between the words

print(combined_str)
# Output: Hello World
  1. Repetition (*): The * operator can be used to repeat a string a certain number of times. Here’s an example:
# Using the * operator to repeat a string
str1 = "Hello "
repeated_str = str1 * 3  # Repeating the string 3 times

print(repeated_str)
# Output: Hello Hello Hello 
  1. Membership (in): The in operator can be used to check if a substring exists within a string. It returns True if the substring is found, and False otherwise. Here’s an example:
# Using the 'in' operator to check membership
sentence = "Python is awesome!"

# Checking if a substring exists within the string
substring = "Python"
result = substring in sentence

print(result)
# Output: True
  1. Indexing ([]): The [] operator can be used to access individual characters within a string. You can use a positive index to access characters from the beginning of the string, and a negative index to access characters from the end of the string. Here’s an example:
# Using the [] operator for indexing a string
my_string = "Python"

# Accessing characters using positive indices
first_char = my_string[0]  # First character
last_char = my_string[5]   # Last character (index 5 for "n")

print("First character:", first_char)  # Output: P
print("Last character:", last_char)    # Output: n

# Accessing characters using negative indices
second_last_char = my_string[-2]  # Second last character (index -2 for "o")
print("Second last character:", second_last_char)  # Output: o
  1. Slicing ([start:end]): The [] operator can also be used to extract a substring (or slice) from a string. The start argument specifies the starting index of the slice (inclusive), and the end argument specifies the ending index of the slice (exclusive). Here’s an example:
# Using the [] operator for string slicing
my_string = "Python Programming"

# Extracting a substring using slicing
substring = my_string[0:6]  # From index 0 to 5 (6 is exclusive)
print(substring)  # Output: Python
  1. Comparison (==, !=, <, <=, >, >=): The comparison operators can be used to compare two strings alphabetically. The == operator returns True if the two strings are equal, and False otherwise. The != operator returns True if the two strings are not equal, and False otherwise. The < and > operators return True if the left string is alphabetically less than or greater than the right string, respectively. The <= and >= operators return True if the left string is alphabetically less than or equal to or greater than or equal to the right string, respectively. Here’s an example:
# Comparison of strings using various operators
string1 = "Apple"
string2 = "Banana"

# Checking if the strings are equal
print(string1 == string2)  # Output: False

# Checking if the strings are not equal
print(string1 != string2)  # Output: True

# Checking if string1 is alphabetically less than string2
print(string1 < string2)   # Output: True

# Checking if string1 is alphabetically greater than string2
print(string1 > string2)   # Output: False

# Checking if string1 is alphabetically less than or equal to string2
print(string1 <= string2)  # Output: True

# Checking if string1 is alphabetically greater than or equal to string2
print(string1 >= string2)  # Output: False

String indexing and slicing:

Indexing:

Indexing: Each character in a string is assigned an index starting from 0. You can access a particular character in a string using its index. Here’s an example:

# Using indexing to access characters in a string
my_string = "Python"

# Accessing individual characters using their indices
first_char = my_string[0]  # First character
second_char = my_string[1]  # Second character
last_char = my_string[5]  # Last character

print("First character:", first_char)  # Output: P
print("Second character:", second_char)  # Output: y
print("Last character:", last_char)  # Output: n
Slicing:

You can extract a portion of a string using slicing. Slicing is done using the [] operator, with two indices separated by a colon (:) inside the brackets. Here’s an example:

# Using slicing to extract a portion of a string
my_string = "Python Programming"

# Slicing from index 0 to 6 (exclusive of index 6)
substring = my_string[0:6]  # This gives 'Python'

print(substring)  # Output: Python

In the example above, my_string[0:5] returns the first five characters of the string, my_string[:5] returns all the characters up to the fifth character, and my_string[-5:] returns the characters from the fifth-last to the last character.

Note that the first index in a slice is inclusive and the second index is exclusive. So, my_string[0:5] returns characters from index 0 to index 4, but not the character at index 5.

In addition to the two indices separated by a colon, you can also add a third index to specify the step value. Here’s an example:

# Using slicing with a step
my_string = "Python Programming"

# Extracting every second character from index 0 to index 12
substring = my_string[0:13:2]  # From index 0 to 12, taking every second character

print(substring)  # Output: Pto rg

String functions:

  1. `len()`: Returns the length of a string. Here’s an example:
# Using len() to get the length of a string
my_string = "Python Programming"

# Get the length of the string
length = len(my_string)

print("The length of the string is:", length)  # Output: 18
  1. `lower()`: Converts all characters in a string to lowercase. Here’s an example:
# Using lower() to convert string to lowercase
my_string = "Python Programming"

# Convert the string to lowercase
lowercase_string = my_string.lower()

print("Original string:", my_string)  # Output: Python Programming
print("Lowercase string:", lowercase_string)  # Output: python programming
  1. `upper()`: Converts all characters in a string to uppercase. Here’s an example:
# Using upper() to convert string to uppercase
my_string = "Python Programming"

# Convert the string to uppercase
uppercase_string = my_string.upper()

print("Original string:", my_string)  # Output: Python Programming
print("Uppercase string:", uppercase_string)  # Output: PYTHON PROGRAMMING
  1. `title()`: Capitalizes the first character of each word in a string. Here’s an example:
# Using title() to capitalize the first character of each word
my_string = "python programming is fun"

# Convert the string to title case
title_string = my_string.title()

print("Original string:", my_string)  # Output: python programming is fun
print("Title case string:", title_string)  # Output: Python Programming Is Fun
  1. `capitalize()`: Capitalizes the first character of a string. Here’s an example:
# Using capitalize() to capitalize the first character of a string
my_string = "python programming"

# Capitalize the first character
capitalized_string = my_string.capitalize()

print("Original string:", my_string)  # Output: python programming
print("Capitalized string:", capitalized_string)  # Output: Python programming
  1. `swapcase()`: Swaps the case of all characters in a string. Here’s an example:
# Using swapcase() to swap the case of all characters in a string
my_string = "Python Programming"

# Swap the case of all characters
swapped_string = my_string.swapcase()

print("Original string:", my_string)  # Output: Python Programming
print("Swapped case string:", swapped_string)  # Output: pYTHON pROGRAMMING
  1. `count()`: Returns the number of occurrences of a substring in a string. Here’s an example:
# Using count() to count occurrences of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Count the occurrences of the word "Python"
count_python = my_string.count("Python")

print("Occurrences of 'Python':", count_python)  # Output: 2
  1. `find()`: Returns the index of the first occurrence of a substring in a string. Here’s an example:
# Using find() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."

# Find the index of the first occurrence of "Python"
index_python = my_string.find("Python")

print("Index of 'Python':", index_python)  # Output: 0
  1. `rfind()`: Returns the index of the last occurrence of a substring in a string.
# Using rfind() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Find the index of the last occurrence of "Python"
last_index_python = my_string.rfind("Python")

print("Index of the last 'Python':", last_index_python)  # Output: 36

       10. `index()`: Like `find()`, but raises a `ValueError` if the substring is not found.

# Using index() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."

# Find the index of the first occurrence of "Python"
index_python = my_string.index("Python")

print("Index of 'Python':", index_python)  # Output: 0
  1. `rindex()`: Like `rfind()`, but raises a `ValueError` if the substring is not found.
# Using rindex() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Find the index of the last occurrence of "Python"
last_index_python = my_string.rindex("Python")

print("Index of the last 'Python':", last_index_python)  # Output: 36
  1. `startswith()`: Returns `True` if a string starts with a specified prefix, otherwise `False`.
# Using startswith() to check if the string starts with a specified prefix
my_string = "Python programming is fun."

# Check if the string starts with "Python"
starts_with_python = my_string.startswith("Python")

print("Starts with 'Python':", starts_with_python)  # Output: True
  1. `endswith()`: Returns `True` if a string ends with a specified suffix, otherwise `False`.
# Using endswith() to check if the string ends with a specified suffix
my_string = "Python programming is fun."

# Check if the string ends with "fun."
ends_with_fun = my_string.endswith("fun.")

print("Ends with 'fun.':", ends_with_fun)  # Output: True
  1. `replace()`: Replaces all occurrences of a substring with another substring.
# Using replace() to replace all occurrences of a substring
my_string = "Python is fun. Python is awesome."

# Replace "Python" with "Java"
new_string = my_string.replace("Python", "Java")

print("Original string:", my_string)
print("New string:", new_string)

       15. `strip()`: Removes whitespace (or other characters) from the beginning and end of a string.





  1. `rstrip()`: Removes whitespace (or other characters) from the end of a string.
# Using rstrip() to remove trailing whitespace
my_string = "Hello, world!    "

# Remove the trailing whitespace
new_string = my_string.rstrip()

print("Original string:", repr(my_string))
print("New string:", repr(new_string))
  1. `lstrip()`: Removes whitespace (or other characters) from the beginning of a string.
# Using lstrip() to remove leading whitespace
my_string = "    Hello, world!"

# Remove the leading whitespace
new_string = my_string.lstrip()

print("Original string:", repr(my_string))
print("New string:", repr(new_string))
  1. `split()`: Splits a string into a list of substrings using a specified delimiter.
# Using split() to split a string into a list of words
my_string = "Python is fun!"

# Split the string by whitespace (default behavior)
words = my_string.split()

print("List of words:", words)
  1. `rsplit()`: Splits a string from the right into a list of substrings using a specified delimiter.
# Using rsplit() to split a string from the right
my_string = "Python is fun and Python is awesome"

# Split the string by whitespace from the right
words = my_string.rsplit()

print("List of words:", words)

The separator used is the comma, which is passed as an argument to the rsplit() method. The 1 argument is used to specify that only one splitting should occur, which in this case splits the last fruit from the first two. Finally, we print the list of fruits.

       20. `join()`: Joins a list of strings into a single string using a specified delimiter.

# Joining with a space
words = ["Hello", "world", "Python", "rocks!"]
sentence = " ".join(words)
print(sentence)  # Output: "Hello world Python rocks!"

# Joining with a comma
items = ["apple", "banana", "cherry"]
csv_line = ",".join(items)
print(csv_line)  # Output: "apple,banana,cherry"

# Joining with a hyphen
letters = ["a", "b", "c", "d"]
hyphenated = "-".join(letters)
print(hyphenated)  # Output: "a-b-c-d"
  1. `isalnum()`: Returns `True` if a string contains only alphanumeric characters, otherwise `False`.
# String with only letters and numbers
print("Hello123".isalnum())  # Output: True

# String with only letters
print("Python".isalnum())  # Output: True

# String with only numbers
print("2024".isalnum())  # Output: True

# String with a space
print("Hello World".isalnum())  # Output: False

# String with special characters
print("Hello@123".isalnum())  # Output: False

# Empty string
print("".isalnum())  # Output: False
  1. `isalpha()`: Returns `True` if a string contains only alphabetic characters, otherwise `False`.
# String with only letters
print("Python".isalpha())  # Output: True

# String with a space
print("Hello World".isalpha())  # Output: False

# String with numbers
print("Python3".isalpha())  # Output: False

# String with special characters
print("Hello!".isalpha())  # Output: False

# Empty string
print("".isalpha())  # Output: False
  1. `isdigit()`: Returns `True` if a string contains only digits, otherwise `False`.
# String with only digits
print("12345".isdigit())  # Output: True

# String with letters
print("123abc".isdigit())  # Output: False

# String with a space
print("123 456".isdigit())  # Output: False

# Empty string
print("".isdigit())  # Output: False
  1. `islower()`: Returns `True` if all characters in a string are lowercase, otherwise `False`.
# All lowercase letters
print("hello".islower())  # Output: True

# Mixed case
print("Hello".islower())  # Output: False

# Digits and special characters are ignored
print("hello123!".islower())  # Output: True

# Contains an uppercase letter
print("helloWorld".islower())  # Output: False

# Empty string
print("".islower())  # Output: False

      25. `isupper()`: Returns `True` if all characters in a string are uppercase, otherwise `False`.

# All uppercase letters
print("HELLO".isupper())  # Output: True

# Mixed case
print("Hello".isupper())  # Output: False

# Includes digits and symbols
print("HELLO123!".isupper())  # Output: True

# Contains a lowercase letter
print("HELLOworld".isupper())  # Output: False

# Empty string
print("".isupper())  # Output: False
  1. `istitle()`: Returns `True` if a string is titlecased (i.e., the first character of each word is capitalized), otherwise `False`.
# Title-cased string
print("Hello World".istitle())  # Output: True

# Mixed case
print("Hello world".istitle())  # Output: False

# Uppercase string
print("HELLO WORLD".istitle())  # Output: False

# Lowercase string
print("hello world".istitle())  # Output: False

# Single title-cased word
print("Python".istitle())  # Output: True
  1. `isspace()`: Returns `True` if a string contains only whitespace characters, otherwise `False`.
# Only spaces
print("   ".isspace())  # Output: True

# Only tabs
print("\t\t".isspace())  # Output: True

# Newline characters
print("\n\n".isspace())  # Output: True

# Mixed whitespace characters
print(" \t\n".isspace())  # Output: True

# Empty string
print("".isspace())  # Output: False
  1. `maketrans()`: Creates a translation table to be used with the `translate()` function.
# Mapping characters 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table))  # Output: "123de"
  1. `translate()`: Returns a copy of a string with specified characters replaced.
# Create a translation table to replace 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table))  # Output: "123de"
  1. `zfill()`: Pads a numeric string with zeros on the left until the specified width is reached.
# Example using zfill() to pad a string with leading zeros
number = "42"
padded_number = number.zfill(5)

print(padded_number)  # Output: '00042'
  1. `expandtabs()`: Replaces tabs in a string with spaces.
# Example using expandtabs() to replace tabs with spaces
text = "Hello\tWorld\tPython"
expanded_text = text.expandtabs(4)  # Replaces tabs with 4 spaces

print(expanded_text)  # Output: 'Hello   World   Python'
  1. `encode()`: Encodes a string using a specified encoding.
# Encoding a string using UTF-8
my_string = "hello world"
encoded_string = my_string.encode("utf-8")

print(encoded_string)  # Output: b'hello world'

In the example above, we have a string containing the phrase “hello world”. We then use the encode() method to encode the string using the UTF-8 encoding. The resulting encoded string is a bytes object, which is denoted by the “b” prefix in the output.

  1. `format_map()`: Formats a string using a dictionary.
# Using format_map() to format a string using a dictionary
person = {"name": "Alice", "age": 30}

# Format string using the dictionary
formatted_string = "My name is {name} and I am {age} years old.".format_map(person)

print(formatted_string)
  1. `isdecimal()`: Returns `True` if a string contains only decimal characters, otherwise `False`.
# Using isdecimal() to check if a string contains only decimal characters
my_string = "12345"

# Check if the string contains only decimal characters
is_decimal = my_string.isdecimal()

print(is_decimal)  # Output: True
  1. `isnumeric()`: Returns `True` if a string contains only numeric characters, otherwise `False`.
# Using isnumeric() to check if a string contains only numeric characters
my_string = "12345"

# Check if the string is numeric
is_numeric = my_string.isnumeric()

print(is_numeric)  # Output: True
  1. `partition()`:It split the string into parts based on the first occurrence of the substring.
# Using partition() to split a string based on the first occurrence of a substring
my_string = "Hello, world! Welcome to Python."

# Split the string at the first occurrence of ","
result = my_string.partition(",")

print(result)

Python String Programs, Exercises, Examples

Python string is a sequence of characters, such as “hello”. They can be used to represent text in a programming language. Strings can be created by enclosing a sequence of characters between double quotes, such as “hello”, or by using the str() function.

1). Write a Python program to get a string made of the first and the last 2 chars from a given string. If the string length is less than 2, return instead of the empty string

2). Python string program that takes a list of strings and returns the length of the longest string.

3). Python string program to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2).

4). Python string program to reverse a string if it’s length is a multiple of 4.

5). Python string program to count occurrences of a substring in a string.

6). Python string program to test whether a passed letter is a vowel or consonant.

7). Find the longest and smallest word in the input string.

8). Print most simultaneously repeated characters in the input string.

9). Write a Python program to calculate the length of a string with loop logic.

10). Write a Python program to replace the second occurrence of any char with the special character $.
Input = “Programming”
Output = “Prog$am$in$”

11). Write a python program to get to swap the last character of a given string.
Input = “SqaTool”
Output = “IqaTooS”

12). Write a python program to exchange the first and last character of each word from the given string.
Input = “Its Online Learning”
Output = “stI enlino gearninL”

13). Write a python to count vowels from each word in the given string show as dictionary output.
Input = “We are Learning Python Codding”
output = {“We” : 1, “are” : 2, “Learning” : 3, “Python”:1, “Codding”}

14). Write a python to repeat vowels 3 times and consonants 2 times.
Input = “Sqa Tools Learning”
Ouput = “SSqqaaa TToooooollss LLeeeaaarrnniiinngg”

15). Write a python program to re-arrange the string.
Input = “Cricket Plays Virat”
Output = “Virat Plays Cricket”

16). Write a python program to get all the digits from the given string.
Input = “””
Sinak’s 1112 aim is to 1773 create a new generation of people who
understand 444 that an organization’s 5324 success or failure is
based on 555 leadership excellence and not managerial
acumen
“””
Output = [1112, 5324, 1773, 5324, 555]

17). Write a python program to replace the words “Java” with “Python” in the given string.
Input = “JAVA is the Best Programming Language in the Market”
Output = “Python is the Best Programming Language in the Market”

18). Write a Python program to get all the palindrome words from the string.
Input = “Python efe language aakaa hellolleh”
output = [“efe”, “aakaa”, “hellolleh”]

19). Write a Python program to create a string with a given list of words.
Input = [“There”, “are”, “Many”, “Programming”, “Language”]
Output = There are many programming languages.

20). Write a Python program to remove duplicate words from the string.
Input = “John jany sabi row john sabi”
output = “John jany sabi row”

21). Write a Python to remove unwanted characters from the given string.
Input = “Prog^ra*m#ming”
Output = “Programming”

Input = “Py(th)#@&on Pro$*#gram”
Output = “PythonProgram”

22). Write a Python program to find the longest capital letter word from the string.
Input = “Learning PYTHON programming is FUN”
Output = “PYTHON”

23). Write a Python program to get common words from strings.
Input String1 = “Very Good Morning, How are You”
Input String1 = “You are a Good student, keep it up”
Output = “You Good are”

24). Write a Python program to find the smallest and largest word in a given string.
Input = “Learning is a part of life and we strive”
Output = “a”, “Learning”

25). Check whether the given string is a palindrome (similar) or not.
Input= sqatoolssqatools
Output= Given string is not a palindrome

26). Write a program using python to reverse the words in a string.
Input= sqatools python
Output= slootaqs

27). Write a program to calculate the length of a string.
Input= “python”
Output = 6

28). Write a program to calculate the frequency of each character in a string.
Input = “sqatools”
Output = {‘s’:2, ‘q’:1, ‘a’: 1, ‘t’:1,‘o’:2, ‘l’:1, ‘s’:1}

29). Write a program to combine two strings into one.
Input: 
A = ’abc’
B = ’def’
Output = abcdef

30). Write a program to print characters at even places in a string.
Input = ‘sqatools’
Output = saol

31). Write a program to check if a string has a number or not.
Input = ‘python1’
Output = ‘Given string have a number’

32). Write a python program to count the number of vowels in a string.
Input= ‘I am learning python’
Output= 6

33). Write a python program to count the number of consonants in a string.
Input= ‘sqltools’
Output= 6

34). Write a program to print characters at odd places in a string.
Input = ‘abcdefg’
Output = ‘bdf’

35). Write a program to remove all duplicate characters from a given string in python.
Input = ‘sqatools’
Output = ‘sqatol’

36). Write a program to check if a string has a special character or not
Input = ‘python$$#sqatools’
Output =  ‘Given string has special characters

37). Write a program to exchange the first and last letters of the string
Input = We are learning python
Output = ne are learning pythoW

38). Write a program to convert all the characters in a string to Upper Case.
Input = ‘I live in pune’
Output = ‘I LIVE IN PUNE’

39). Write a program to remove a new line from a string using python.
Input = ‘objectorientedprogramming\n’
Output = ‘Objectorientedprogramming’

40). Write a python program to split and join a string
Input =‘Hello world’
Output = [‘Hello’, ‘world’]
                 Hello-world

41). Write a program to print floating numbers up to 3 decimal places and convert it to string.
Input = 2.14652
Output= 2.146

42). Write a program to convert numeric words to numbers.
Input = ‘five four three two one’
Output = 54321

43). Write a python program to find the location of a word in a string
Input Word = ‘problems’
Input string = ‘ I am solving problems based on strings’
Output = 4

44). Write a program to count occurrences of a word in a string.

Word = ‘food’
Input str = ‘ I want to eat fast food’
Occurrences output= 1

Word = ‘are’
Input str = “We are learning Python, wow are you”
Occurrences output = 2 

45). Write a python program to find the least frequent character in a string.
Input =  ‘abcdabdggfhf’
Output = ‘c’

46). Find the words greater than the given length.
Ex length = 3
Input = ‘We are learning python’
Output – ‘learning python’

47). Write a program to get the first 4 characters of a string.
Input = ‘Sqatools’
Output = ‘sqat’

48). Write a Python program to get a string made of the first 2 and the last 2 chars from a given string.
Input = ‘Sqatools’
Output = ‘Sqls’ 

49). Write a python program to print the mirror image of the string.
Input = ‘Python’
Output = ‘nohtyp 

50). Write a python program to split strings on vowels
Input = ‘qwerty’
Output = ‘qw rty’

51). Write a python program to replace multiple words with certain words.
Input = “I’m learning python at Sqatools”
Replace python with SQA  and sqatools with TOOLS 
Output = “I’m learning SQA at TOOLS “

52). Write a python program to replace different characters in the string at once.
Input = ‘Sqatool python’
Replace a with 1,
Replace t with 2,
Replace o with 3
Output = ‘sq1233l py2h3n”

53). Write a python program to remove empty spaces from a list of strings.
Input = [‘Python’, ‘ ‘, ‘ ‘, ‘sqatools’]
Output = [‘Python’, ‘sqatools’] 

54).  Write a python program to remove punctuations from a string
Input = ‘Sqatools : is best, for python’
Output = ‘Sqatools is best for python’

55).  Write a python program to find duplicate characters in a string
Input = “hello world”
Output = ‘lo’

56).  Write a python program to check whether the string is a subset of another string or not
Input str1 = “iamlearningpythonatsqatools”
str = ‘pystlmi’
Output = True

57). Write a python program to sort a string
Input = ‘xyabkmp’
Output = ‘abkmpxy’

58). Write a python program to generate a random binary string of a given length.
Input = 8
Output = 10001001

59). Write a python program to check if the substring is present in the string or not
Input string= ‘I live in Pune’
Substring= ‘I live ‘
Output = ‘Yes

60). Write a program to find all substring frequencies in a string.
Input str1 = “abab” 
Output = {‘a’: 2, ‘ab’: 2, ‘aba’: 1,‘abab’: 1, ‘b’: 2, ‘ba’: 1, ‘bab’: 1}  

61). Write a python program to print the index of the character in a string.
Input = ‘Sqatools’
Output = ‘The index of q is 1’

62). Write a program to strip spaces from a string.
Input = ‘    sqaltoolspythonfun     ‘ 
Output = ‘ sqaltoolspythonfun’

63). Write a program to check whether a string contains all letters of the alphabet or not.
Input = ‘abcdgjksoug’
Output = False

64). Write a python program to convert a string into a list of words.
Input = ‘learning python is fun’
Output = [learning, python, is, fun] 

65). Write a python program to swap commas and dots in a string.
Input = sqa,tools.python
Output = sqa.tools,python

66). Write a python program to count and display the vowels in a string
Input = ‘welcome to Sqatools’
Output = 7

67). Write a Python program to split a string on the last occurrence of the delimiter. 
Input = ‘l,e,a,r,n,I,n,g,p,y,t,h,o,n’
Output = [‘l,e,a,r,n,I,n,g,p,y,t,h,o ‘ ,’n’]

68). Write a Python program to find the first repeated word in a given string. 
Input = ‘ab bc ca ab bd’
Output = ‘ab’

69). Write a program to find the second most repeated word in a given string using python.
Input = ‘ab bc ac ab bd ac nk hj ac’
Output = (‘ab’, 2)

70). Write a Python program to remove spaces from a given string.
Input = ‘python at sqatools’
Output = ‘pythonatsqatools’

71). Write a Python program to capitalize the first and last letters of each word of a given string.
Input = ‘this is my first program’
Output = ‘ThiS IS MY FirsT PrograM’

72). Write a Python program to calculate the sum of digits of a given string.
Input = ’12sqatools78′
Output = 18

73). Write a Python program to remove zeros from an IP address. 
Input = 289.03.02.054
Output = 289.3.2.54

74). Write a program to find the maximum length of consecutive 0’s in a given binary string using python.
Input = 10001100000111
Output = 5 

75). Write a program to remove all consecutive duplicates of a given string using python.
Input = ‘xxxxyy’
Output = ‘xy’

76). Write a program to create strings from a given string. Create a string that consists of multi-time occurring characters in the said string using python.
Input = “aabbcceffgh”
Output = ‘abcf’

77). Write a Python program to create a string from two given strings combining uncommon characters of the said strings.  

Input string :
s1 = ‘abcdefg’
s2 = ‘xyzabcd’
Output string : ‘efgxyz’

78). Write a Python code to remove all characters except the given character in a string. 
Input = “Sqatools python”
Remove all characters except S
Output = ‘S’

79). Write a program to count all the Uppercase, Lowercase, special character and numeric values in a given string using python.
Input = ‘@SqaTools.lin’
Output:
Special characters: 1
Uppercase characters: 2
Lowercase characters: 8

80). Write a Python program to count a number of non-empty substrings of a given string.
Input a string = ‘sqatools12’
Number of substrings = 55

81). Write a program to remove unwanted characters from a given string using python.
Input = ‘sqa****too^^{ls’
Output = ‘Sqatools’

82). Write a program to find the string similarity between two given strings using python.
Input
Str1 = ‘Learning is fun in Sqatools’
Str2 = ‘Sqatools Online Learning Platform’

Output :
Similarity : 0.4

83). Write a program to extract numbers from a given string using python.
Input = ‘python 456 self learning 89’
Output = [456, 89]

84). Write a program to split a given multiline string into a list of lines using python.
Input =”’This string Contains
Multiple
Lines”’
Output = [‘This string Contains’, ‘Multiple’, ‘Lines’]

85). Write a program to add two strings as they are numbers using python.
Input :
a=’3′, b=’7′
Output  = ’10’

86). Write a program to extract name from a given email address using python.
Input = ‘student1@gmail.com’
Output = ‘student’

87). Write a  program that counts the number of leap years within the range of years using python. The range of years should be accepted as a string. 

(“1981-2001)  =  Total leap year 5

88). Write a program to insert space before every capital letter appears in a given word using python. 
Input = ‘SqaTools pyThon’
Output = ‘ Sqa Tools py Thon’ 

89). Write a program to uppercase half string using python.
Input = ‘banana’
Output = ‘banANA’

90). Write a program to split and join a string using “-“.
Input = ‘Sqatools is best’
Output = ‘Sqatools-is-best’

91). Write a python program to find permutations of a given string using in built function.
Input  = ‘CDE’
Output = [‘CDE’, ‘CED’ ‘EDC’, ‘ECD’, ‘DCE’, ‘DEC’]

92). Write a program to avoid spaces in string and get the total length
Input = ‘sqatools is best for learning python’
Output = 31

93). Write a program to accept a string that contains only vowels
Input = ‘python’
Output- ‘not accepted’

Input = ‘aaieou’
Output = ‘accepted’

94). Write a program to remove the kth element from the string
K=2
Input = ‘sqatools’
Output = ‘sqtools’

95). Write a program to check if a given string is binary or not.
Hint: Binary numbers only contain 0 or 1.

Input = ‘01011100’
Output = yes

Input = ‘sqatools 100’
Output = ‘No’

96). Write a program to add ‘ing’ at the end of the string using python.
Input = ‘xyz’
Output = ‘xyzing’

97). Write a program to add ly at the end of the string if the given string ends with ing.
Input = ‘winning’
Output = ‘winningly’

98). Write a program to reverse words in a string using python.
Input = ‘string problems’
Output = ‘problems string’

99). Write a program to print the index of each character in a string.
Input =  ‘sqatools’
Output :
Index of s is 0
Index of q is 1
Index of a is 2
Index of t is 3
Index of o is 4
Index of o is 5
Index of l is 6
Index of s is 7

100). Write a program to find the first repeated character in a string and its index.
Input = ‘sqatools’
Output = (s,0)

101). Write a program to swap cases of a given string using python.
Input = ‘Learning Python’
Output = ‘lEARNING pYTHON’

102). Write a program to remove repeated characters in a string and replace it with a single letter using python.
Input = ‘aabbccdd’
Output = ‘cabd’

103). Write a program to print a string 3 times using python.
Input = ‘sqatools’
Output = ‘sqatoolssqatoolssqatools’

104). Write a program to print each character on a new line using python.
Input = ‘python’
Output:
p
y
t
h
o
n

105). Write a program to get all the email id’s from given string using python.
Input str = “”” We have some employee whos john@gmail.com email id’s are randomly distributed jay@lic.com we want to get hari@facebook.com all the email mery@hotmail.com id’s from this given string.”””
Output = [‘john@gmail.com’, ‘ jay@lic.com’, ‘hari@facebook.com’, ‘mery@hotmail.com’ ]

106). Write a program to get a list of all the mobile numbers from the given string using python.
Input str = “”” We have 2233 some employee 8988858683 whos 3455 mobile numbers are randomly distributed 2312245566 we want 453452 to get 4532892234 all the mobile numbers 9999234355  from this given string.”””
Output = [‘8988858683’, ‘2312245566’, ‘4532892234’, ‘9999234355’]

Python String Programs, Exercises

Python string is a sequence of characters, such as “hello”. They can be used to represent text in a programming language. Strings can be created by enclosing a sequence of characters between double quotes, such as “hello”, or by using the str() function.

1). Write a Python program to get a string made of the first and the last 2 chars from a given string. If the string length is less than 2, return instead of the empty string

2). Python string program that takes a list of strings and returns the length of the longest string.

3). Python string program to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2).

4). Python string program to reverse a string if it’s length is a multiple of 4.

5). Python string program to count occurrences of a substring in a string.

6). Python string program to test whether a passed letter is a vowel or consonant.

7). Find the longest and smallest word in the input string.

8). Print most simultaneously repeated characters in the input string.

9). Write a Python program to calculate the length of a string with loop logic.

10). Write a Python program to replace the second occurrence of any char with the special character $.
Input = “Programming”
Output = “Prog$am$in$”

11). Write a python program to get to swap the last character of a given string.
Input = “SqaTool”
Output = “IqaTooS”

12). Write a python program to exchange the first and last character of each word from the given string.
Input = “Its Online Learning”
Output = “stI enlino gearninL”

13). Write a python to count vowels from each word in the given string show as dictionary output.
Input = “We are Learning Python Codding”
output = {“We” : 1, “are” : 2, “Learning” : 3, “Python”:1, “Codding”}

14). Write a python to repeat vowels 3 times and consonants 2 times.
Input = “Sqa Tools Learning”
Ouput = “SSqqaaa TToooooollss LLeeeaaarrnniiinngg”

15). Write a python program to re-arrange the string.
Input = “Cricket Plays Virat”
Output = “Virat Plays Cricket”

16). Write a python program to get all the digits from the given string.
Input = “””
Sinak’s 1112 aim is to 1773 create a new generation of people who
understand 444 that an organization’s 5324 success or failure is
based on 555 leadership excellence and not managerial
acumen
“””
Output = [1112, 5324, 1773, 5324, 555]

17). Write a python program to replace the words “Java” with “Python” in the given string.
Input = “JAVA is the Best Programming Language in the Market”
Output = “Python is the Best Programming Language in the Market”

18). Write a Python program to get all the palindrome words from the string.
Input = “Python efe language aakaa hellolleh”
output = [“efe”, “aakaa”, “hellolleh”]

19). Write a Python program to create a string with a given list of words.
Input = [“There”, “are”, “Many”, “Programming”, “Language”]
Output = There are many programming languages.

20). Write a Python program to remove duplicate words from the string.
Input = “John jany sabi row john sabi”
output = “John jany sabi row”

21). Write a Python to remove unwanted characters from the given string.
Input = “Prog^ra*m#ming”
Output = “Programming”

Input = “Py(th)#@&on Pro$*#gram”
Output = “PythonProgram”

22). Write a Python program to find the longest capital letter word from the string.
Input = “Learning PYTHON programming is FUN”
Output = “PYTHON”

23). Write a Python program to get common words from strings.
Input String1 = “Very Good Morning, How are You”
Input String1 = “You are a Good student, keep it up”
Output = “You Good are”

24). Write a Python program to find the smallest and largest word in a given string.
Input = “Learning is a part of life and we strive”
Output = “a”, “Learning”

25). Check whether the given string is a palindrome (similar) or not.
Input= sqatoolssqatools
Output= Given string is not a palindrome

26). Write a program using python to reverse the words in a string.
Input= sqatools python
Output= slootaqs

27). Write a program to calculate the length of a string.
Input= “python”
Output = 6

28). Write a program to calculate the frequency of each character in a string.
Input = “sqatools”
Output = {‘s’:2, ‘q’:1, ‘a’: 1, ‘t’:1,‘o’:2, ‘l’:1, ‘s’:1}

29). Write a program to combine two strings into one.
Input: 
A = ’abc’
B = ’def’
Output = abcdef

30). Write a program to print characters at even places in a string.
Input = ‘sqatools’
Output = saol

31). Write a program to check if a string has a number or not.
Input = ‘python1’
Output = ‘Given string have a number’

32). Write a python program to count the number of vowels in a string.
Input= ‘I am learning python’
Output= 6

33). Write a python program to count the number of consonants in a string.
Input= ‘sqltools’
Output= 6

34). Write a program to print characters at odd places in a string.
Input = ‘abcdefg’
Output = ‘bdf’

35). Write a program to remove all duplicate characters from a given string in python.
Input = ‘sqatools’
Output = ‘sqatol’

36). Write a program to check if a string has a special character or not
Input = ‘python$$#sqatools’
Output =  ‘Given string has special characters

37). Write a program to exchange the first and last letters of the string
Input = We are learning python
Output = ne are learning pythoW

38). Write a program to convert all the characters in a string to Upper Case.
Input = ‘I live in pune’
Output = ‘I LIVE IN PUNE’

39). Write a program to remove a new line from a string using python.
Input = ‘objectorientedprogramming\n’
Output = ‘Objectorientedprogramming’

40). Write a python program to split and join a string
Input =‘Hello world’
Output = [‘Hello’, ‘world’]
                 Hello-world

41). Write a program to print floating numbers up to 3 decimal places and convert it to string.
Input = 2.14652
Output= 2.146

42). Write a program to convert numeric words to numbers.
Input = ‘five four three two one’
Output = 54321

43). Write a python program to find the location of a word in a string
Input Word = ‘problems’
Input string = ‘ I am solving problems based on strings’
Output = 4

44). Write a program to count occurrences of a word in a string.

Word = ‘food’
Input str = ‘ I want to eat fast food’
Occurrences output= 1

Word = ‘are’
Input str = “We are learning Python, wow are you”
Occurrences output = 2 

45). Write a python program to find the least frequent character in a string.
Input =  ‘abcdabdggfhf’
Output = ‘c’

46). Find the words greater than the given length.
Ex length = 3
Input = ‘We are learning python’
Output – ‘learning python’

47). Write a program to get the first 4 characters of a string.
Input = ‘Sqatools’
Output = ‘sqat’

48). Write a Python program to get a string made of the first 2 and the last 2 chars from a given string.
Input = ‘Sqatools’
Output = ‘Sqls’ 

49). Write a python program to print the mirror image of the string.
Input = ‘Python’
Output = ‘nohtyp 

50). Write a python program to split strings on vowels
Input = ‘qwerty’
Output = ‘qw rty’

51). Write a python program to replace multiple words with certain words.
Input = “I’m learning python at Sqatools”
Replace python with SQA  and sqatools with TOOLS 
Output = “I’m learning SQA at TOOLS “

52). Write a python program to replace different characters in the string at once.
Input = ‘Sqatool python’
Replace a with 1,
Replace t with 2,
Replace o with 3
Output = ‘sq1233l py2h3n”

53). Write a python program to remove empty spaces from a list of strings.
Input = [‘Python’, ‘ ‘, ‘ ‘, ‘sqatools’]
Output = [‘Python’, ‘sqatools’] 

54).  Write a python program to remove punctuations from a string
Input = ‘Sqatools : is best, for python’
Output = ‘Sqatools is best for python’

55).  Write a python program to find duplicate characters in a string
Input = “hello world”
Output = ‘lo’

56).  Write a python program to check whether the string is a subset of another string or not
Input str1 = “iamlearningpythonatsqatools”
str = ‘pystlmi’
Output = True

57). Write a python program to sort a string
Input = ‘xyabkmp’
Output = ‘abkmpxy’

58). Write a python program to generate a random binary string of a given length.
Input = 8
Output = 10001001

59). Write a python program to check if the substring is present in the string or not
Input string= ‘I live in Pune’
Substring= ‘I live ‘
Output = ‘Yes

60). Write a program to find all substring frequencies in a string.
Input str1 = “abab” 
Output = {‘a’: 2, ‘ab’: 2, ‘aba’: 1,‘abab’: 1, ‘b’: 2, ‘ba’: 1, ‘bab’: 1}  

61). Write a python program to print the index of the character in a string.
Input = ‘Sqatools’
Output = ‘The index of q is 1’

62). Write a program to strip spaces from a string.
Input = ‘    sqaltoolspythonfun     ‘ 
Output = ‘ sqaltoolspythonfun’

63). Write a program to check whether a string contains all letters of the alphabet or not.
Input = ‘abcdgjksoug’
Output = False

64). Write a python program to convert a string into a list of words.
Input = ‘learning python is fun’
Output = [learning, python, is, fun] 

65). Write a python program to swap commas and dots in a string.
Input = sqa,tools.python
Output = sqa.tools,python

66). Write a python program to count and display the vowels in a string
Input = ‘welcome to Sqatools’
Output = 7

67). Write a Python program to split a string on the last occurrence of the delimiter. 
Input = ‘l,e,a,r,n,I,n,g,p,y,t,h,o,n’
Output = [‘l,e,a,r,n,I,n,g,p,y,t,h,o ‘ ,’n’]

68). Write a Python program to find the first repeated word in a given string. 
Input = ‘ab bc ca ab bd’
Output = ‘ab’

69). Write a program to find the second most repeated word in a given string using python.
Input = ‘ab bc ac ab bd ac nk hj ac’
Output = (‘ab’, 2)

70). Write a Python program to remove spaces from a given string.
Input = ‘python at sqatools’
Output = ‘pythonatsqatools’

71). Write a Python program to capitalize the first and last letters of each word of a given string.
Input = ‘this is my first program’
Output = ‘ThiS IS MY FirsT PrograM’

72). Write a Python program to calculate the sum of digits of a given string.
Input = ’12sqatools78′
Output = 18

73). Write a Python program to remove zeros from an IP address. 
Input = 289.03.02.054
Output = 289.3.2.54

74). Write a program to find the maximum length of consecutive 0’s in a given binary string using python.
Input = 10001100000111
Output = 5 

75). Write a program to remove all consecutive duplicates of a given string using python.
Input = ‘xxxxyy’
Output = ‘xy’

76). Write a program to create strings from a given string. Create a string that consists of multi-time occurring characters in the said string using python.
Input = “aabbcceffgh”
Output = ‘abcf’

77). Write a Python program to create a string from two given strings combining uncommon characters of the said strings.  

Input string :
s1 = ‘abcdefg’
s2 = ‘xyzabcd’
Output string : ‘efgxyz’

78). Write a Python code to remove all characters except the given character in a string. 
Input = “Sqatools python”
Remove all characters except S
Output = ‘S’

79). Write a program to count all the Uppercase, Lowercase, special character and numeric values in a given string using python.
Input = ‘@SqaTools.lin’
Output:
Special characters: 1
Uppercase characters: 2
Lowercase characters: 8

80). Write a Python program to count a number of non-empty substrings of a given string.
Input a string = ‘sqatools12’
Number of substrings = 55

81). Write a program to remove unwanted characters from a given string using python.
Input = ‘sqa****too^^{ls’
Output = ‘Sqatools’

82). Write a program to find the string similarity between two given strings using python.
Input
Str1 = ‘Learning is fun in Sqatools’
Str2 = ‘Sqatools Online Learning Platform’

Output :
Similarity : 0.4

83). Write a program to extract numbers from a given string using python.
Input = ‘python 456 self learning 89’
Output = [456, 89]

84). Write a program to split a given multiline string into a list of lines using python.
Input =”’This string Contains
Multiple
Lines”’
Output = [‘This string Contains’, ‘Multiple’, ‘Lines’]

85). Write a program to add two strings as they are numbers using python.
Input :
a=’3′, b=’7′
Output  = ’10’

86). Write a program to extract name from a given email address using python.
Input = ‘student1@gmail.com’
Output = ‘student’

87). Write a  program that counts the number of leap years within the range of years using python. The range of years should be accepted as a string. 

(“1981-2001)  =  Total leap year 5

88). Write a program to insert space before every capital letter appears in a given word using python. 
Input = ‘SqaTools pyThon’
Output = ‘ Sqa Tools py Thon’ 

89). Write a program to uppercase half string using python.
Input = ‘banana’
Output = ‘banANA’

90). Write a program to split and join a string using “-“.
Input = ‘Sqatools is best’
Output = ‘Sqatools-is-best’

91). Write a python program to find permutations of a given string using in built function.
Input  = ‘CDE’
Output = [‘CDE’, ‘CED’ ‘EDC’, ‘ECD’, ‘DCE’, ‘DEC’]

92). Write a program to avoid spaces in string and get the total length
Input = ‘sqatools is best for learning python’
Output = 31

93). Write a program to accept a string that contains only vowels
Input = ‘python’
Output- ‘not accepted’

Input = ‘aaieou’
Output = ‘accepted’

94). Write a program to remove the kth element from the string
K=2
Input = ‘sqatools’
Output = ‘sqtools’

95). Write a program to check if a given string is binary or not.
Hint: Binary numbers only contain 0 or 1.

Input = ‘01011100’
Output = yes

Input = ‘sqatools 100’
Output = ‘No’

96). Write a program to add ‘ing’ at the end of the string using python.
Input = ‘xyz’
Output = ‘xyzing’

97). Write a program to add ly at the end of the string if the given string ends with ing.
Input = ‘winning’
Output = ‘winningly’

98). Write a program to reverse words in a string using python.
Input = ‘string problems’
Output = ‘problems string’

99). Write a program to print the index of each character in a string.
Input =  ‘sqatools’
Output :
Index of s is 0
Index of q is 1
Index of a is 2
Index of t is 3
Index of o is 4
Index of o is 5
Index of l is 6
Index of s is 7

100). Write a program to find the first repeated character in a string and its index.
Input = ‘sqatools’
Output = (s,0)

101). Write a program to swap cases of a given string using python.
Input = ‘Learning Python’
Output = ‘lEARNING pYTHON’

102). Write a program to remove repeated characters in a string and replace it with a single letter using python.
Input = ‘aabbccdd’
Output = ‘cabd’

103). Write a program to print a string 3 times using python.
Input = ‘sqatools’
Output = ‘sqatoolssqatoolssqatools’

104). Write a program to print each character on a new line using python.
Input = ‘python’
Output:
p
y
t
h
o
n

105). Write a program to get all the email id’s from given string using python.
Input str = “”” We have some employee whos john@gmail.com email id’s are randomly distributed jay@lic.com we want to get hari@facebook.com all the email mery@hotmail.com id’s from this given string.”””
Output = [‘john@gmail.com’, ‘ jay@lic.com’, ‘hari@facebook.com’, ‘mery@hotmail.com’ ]

106). Write a program to get a list of all the mobile numbers from the given string using python.
Input str = “”” We have 2233 some employee 8988858683 whos 3455 mobile numbers are randomly distributed 2312245566 we want 453452 to get 4532892234 all the mobile numbers 9999234355  from this given string.”””
Output = [‘8988858683’, ‘2312245566’, ‘4532892234’, ‘9999234355’]