Python Strings Practice Programs For Beginners

# Python Strings Practice Programs For Beginners

clickHere
Updated on Feb 23, 2022 09:54 IST

Let us now look at some common Python practice programs based on strings that will help you master your foundations. I suggest you try to code by yourself before trying to view the solutions given below. Also, there are plenty of ways to achieve what you want in Python. Take the initiative to explore new ways to solve the problem statements given below.

All right! Let’s get started!

## Write a Python Program to Check if the String is Symmetrical or Palindrome

The objective is to determine whether or not the string is symmetrical and palindrome. A string is said to be symmetrical if both halves of the string are the same, and a string is said to be a palindrome if one half of the string is the opposite of the other half or if the string appears the same whether read forward or backward.

```My_string = input("Enter the string: ")

mid_value = int(len(My_string) / 2)

if len(My_string) % 2 == 0:  # even
first_string = My_string[:mid_value]
second_string = My_string[mid_value:]
else:  # odd
first_string = My_string[:mid_value]
second_string = My_string[mid_value+1:]

# condition to symmetric
if first_string == second_string:
print(My_string, 'Entered string is symmertical')
else:
print(My_string, 'Entered string is not symmertical')

# condition to check palindrome
if first_string == second_string[::-1]:  #you can also use ''.join(reversed(second_str)) [slower]
print(My_string, 'Entered string is palindrome')
else:
print(My_string, 'Entered string is not palindrome')
```

## Write a Python Program to Remove i’th Character From String in Python

There are many ways to remove the i’th character from an entered string! Let’s look into it one by one!!

#### 2. Removing the i’th character from a string using replace() method

```#Function used for removing the i'th character from a string using splitting method

def remove(My_string, i):
x = My_string[ : i]  # Characters before the i-th indexed is stored in a variable a
y = My_string[i + 1: ]     # Characters after the nth indexed is stored in a variable b
return x + y     # Returning string after removing nth indexed character.

#Using string replace() for removing the i'th character from a string

def remove(My_string, a):
for b in range(len(My_string)):
if b == a:
My_string = My_string.replace(My_string[a], "", 1)
return My_string

# Driver Code
if __name__ == '__main__':
My_string = "NaukriLearning"
z = 3 # Remove nth index element

print("string before the i'th character:",My_string)
print("i'th character of the string is removed by splitting method:",remove(My_string, z)) # Print the new string
print("i'th character of the string is removed by replace() method:",remove(My_string, z)) # Print the new string
```

#### 4. Removing the i’th character from a string using join() + list comprehension method

```My_string = "NaukriLearning"

# Removing char at pos 3 using slice + concatenation
new_string = My_string[:2] +  My_string[3:]

# Removing char at pos 3 using join() + list comprehension
new_string1 = ''.join([My_string[e] for e in range(len(My_string)) if e != 3])

print ("The original string is : " + My_string)
print ("The string after removal of i'th character using slicing and concatenation: " + new_string) # Print the new string
print ("The string after removal of i'th character using str.join() and list comprehension: " + new_string) # Print the new string
```

## Write a Python Program to Find the Length of a String

Here are 4 ways of finding the length of strings as mentioned below!

1. Using for loop and in operator
2. Using while loop and Slicing
3. Using string methods join and count
4. Using the built-in function len
```My_string = "NaukriLearning"
#Using for loop and in operator
def Length(My_string):
count = 0
for i in My_string:
count += 1
return count

#Using while loop and Slicing
def Length(My_string):
count = 0
while My_string[count:]:
count += 1
return count

#Using string methods join and count
def Length(My_string):
if not My_string:
return 0
else:
some_random_string = 'xyz'
return ((some_random_string).join(My_string)).count(some_random_string) + 1
#Using the built-in function len
print("length of the String using for loop and in operator:", len(My_string))
print("length of the String Using while loop and Slicing:", Length(My_string))
print("length of the String Using string methods join and count:", Length(My_string))
print("length of the String Using the built-in function len:", Length(My_string))
```

## Write a Python Program to Avoid Spaces in String Length

There are 2 ways of finding the length of strings as mentioned below!

1. Using isspace() + sum()
2. Using sum() + len() + map() + split()
```My_string = "NaukriLearning is best for learning Python"
# isspace() checks for space sum checks count
test_string1 = sum(not chr.isspace() for chr in My_string)
# len() finds individual word Frequency sum() extracts final Frequency
test_string2 = sum(map(len, My_string.split()))
print("The original string is : " + str(My_string))
print("The Characters except spaces are : " + str(test_string1))
print("The Characters except spaces are : " + str(test_string2))
```

## Write a Python Program to Print Even Length Words in a String

You can achieve this by splitting the string into a list of substrings and then for each substring, you need to check if the length is even or odd. Then print the string if it is even.

```def evenwords(My_string):
My_string = My_string.split(' ') # split the string
for even_word in My_string: # iterate in words of string
if len(even_word)%2==0: # if length is even
print(even_word)
# Driver Code
My_string = "NaukriLearning is best for learning Python"
evenwords(My_string)
```

## Write a Python Program Print First Half of the String in Uppercase and the Next Half in Lowercase

First thing is that you need a way to access the first half of the string and then the next half. To achieve this you can use the for loop and range function. The next question is how to get the index of the middle character of the string to divide the string. This you can achieve using the range function and math.ceil(). ceil(y) method returns ceiling value, that is, that smallest number that is greater or equal to y.

Lastly, you can use str.upper and str.lower methods to convert the first half to uppercase and the second half to lowercase respectively.

```import math

My_string = 'NaukriLearning is best for learning Python';

My_string_len = len(My_string) # Storing the length of the string into a variable using string.length function

new_string = '' #Creating an empty string that is used in the future to store the newly created string

#Using of for loops to traverse the string
for i in range(math.ceil(My_string_len/2)):
new_string += My_string[i].upper();

for i in range(math.ceil(My_string_len/2), My_string_len):
new_string += My_string[i].lower();

print("first half of the given string in Uppercase and next half of string in Lowercase is: ",new_string)
```

## Write a Python Program to Capitalize the Alternative Characters of the String

You can achieve this in a simple way by capitalizing the character at the even index and then modifying the characters at the odd index to lowercase. You can use upper(), lower() methods and for loop to execute the above logic.

```My_string = 'naukrilearning is best for learning python'

# Using upper() + lower() + loop for Alternate cases in String
new_string = ""
for string in range(len(My_string)):
if not string % 2 :
new_string = new_string + My_string[string].upper()
else:
new_string = new_string + My_string[string].lower()

print("The original string is : " + str(My_string))

print("Capitalizing alternate characters string is : " + str(new_string))
```

## Write a Python Program to First and Last Characters of Each Word in a String

Here’s the solution to modify the first letter and last letter of every substring to uppercase and the remaining characters of each substring to lowercase.

```def word_capping(My_string):
#Simplify the code by using lambda function
#for capitalizing the first and last letter of words in the string
return ' '.join(map(lambda My_string: My_string[:-1]+My_string[-1].upper(),
My_string.title().split()))

# Driver's code
My_string = 'naukrilearning is best for learning python'
print("String before capitalizing the first and last character of each word in a string:", My_string)
print("String after capitalizing the first and last character of each word in a string:", word_capping(My_string))
```

So, what exactly are we doing here? Firstly we are using a map function that returns a map object (an iterator). The function within the map is then applied to each item of the given iterable, which can be a list, tuple, string, or others. In our case a string.

The map function that we are applying to each element of the iterable is My_string[:-1]+My_string[-1].upper() which converts the last letter off each substring to uppercase. The elements that we are passing are a list of substrings with their first letter capital and the rest of them in lowercase. This is achieved by title() and split() function. The split function separates the string into a list of substrings. Lastly, these modified items are put together to form a string using the join() function.

## Write a Python Program to Count the Number of Digits, Alphabets, and Other Characters in a String

Here we are using isalpha() and isdigit() function and a for loop with if_else statements to count the number of digits, alphabets, and other special characters.

```My_string = "Naukrilearning@123"

alphabets = 0
digits = 0
special_char =0

# To Count Alphabets, Digits and Special Characters in a String using For Loop, isalpha() and isdigit() function
for i in range(len(My_string)):
if(My_string[i].isalpha()):
alphabets = alphabets + 1
elif(My_string[i].isdigit()):
digits = digits + 1
else:
special_char = special_char + 1

print("Total Count of Alphabets in given String:  ", alphabets)
print("Total Count of Digits in given String:  ", digits)
print("Total Count of Special Characters in given String:  ", special_char)
```

## Write a Python Program to Check if a String Starts With the Alphabet and Has Digits

You can check if the first letter of the string is alphabet using isalpha() and isupper() can be used to check if the character at 0th offset (the first character) is capital. Then you can check if the string has digits using isdigit() method. Use variables to set the flag to True or False for both the cases and then apply the ‘and’ operator to achieve the result.

If the first character is the uppercase alphabet and if the string has digits – True

If the first character is the lowercase alphabet and if it string has digits – False

If the first character is a digit (of course then the string will have digits) – False

If the first character is the uppercase alphabet and the string has no digits – False

```def check_String(str):
# initializing flag variable
cap = False
digit = False
# checking for letter and numbers in given string
for z in str:
# if string has started with alphabet letter
if z[0].isalpha() and z[0].isupper():
cap = True
# if string has digit
if z.isdigit():
digit = True
# returning and of flag for checking required condition
return cap and digit

print(check_String (str('naukrilearning')))
print(check_String (str('1naukrilearning1')))
```

## Write a Python Program to Count the Number of Vowels in a String

This is a very basic program that you come across when learning any programming language. The code is pretty straightforward. We are using string indexing operation, if_else statements, for loop and a custom function to achieve the result.

```# Function to check the Vowel
def vowel(chars):
return chars.upper() in ['A', 'E', 'I', 'O', 'U']

# Returns count of vowels in str
def countofVowels(My_string):
count = 0
for i in range(len(My_string)):

# Check for vowel
if vowel(My_string[i]):
count += 1
return count

# Driver Code

# string object
My_string = 'NaukriLearning'

# Total number of Vowels
print("Number of vowels in the given string is:",countofVowels(My_string))
```

## Write a Python Program to Remove All Duplicate Words From a Given String

Firstly we are creating an empty string named res_str, which will have the unique resulting string at the end of the program. We start by checking if each character of the given string is present in res_str. If it is present then we ignore it and go for the next iteration of the for a loop. If the character is not present in res_str, then we add that character to res_str.

```My_string="Naukrilearning"
res_str=""
for character in My_string:
if character not in res_str:
res_str=res_str+character
print(res_str)
k=list("Naukrilearning")
```

## Write a Python Program to Print the Character with Maximum Frequency in a String

Your program needs to print the character in a string that appears maximum times.

from collections import Counter

```from collections import Counter

My_string = "Naukrilearning is best for learning python"

# using collections.Counter() + max() to get Maximum frequency character in String
flag = Counter(My_string)
flag = max(flag, key = flag.get)

print ("The original string is : " + My_string)

print ("The maximum of all characters in Naukrilearning is best for learning python is : " + str(flag))
```

Ok! That looks complex, ain’t it? Well, it really isn’t. Here, we are using Python Counter, which is a container that allows you to count the items in an iterable object, here string. It returns a dictionary object where elements and the count are represented as key-value pairs. Now that you have the count of each character, all you need is to find the one with the maximum count using the max function.

## Write a Python Program to Print the Frequency of Each Character in String

There are 3 different methods by which you check the frequency of each character as shown

1. Using collections.Counter() method
2. Using dict.get() method
3. Using set() + count()
```from collections import Counter

My_string = "Naukrilearning is best for learning python"

# using collections.Counter() to get count of each element in string
flag1 = Counter(My_string)

# using dict.get() to get count of each element in string
flag2 = {}
for keys in My_string:
flag2[keys] = flag2.get(keys, 0) + 1

# using set() + count() to get count of each element in string
flag3 = {i : My_string.count(i) for i in set(My_string)}

print ("Count of all characters in Naukrilearning is best for learning python is :
" , str(flag1))

print ("Count of all characters in Naukrilearning is best for learning python is :
" , str(flag2))

print ("Count of all characters in Naukrilearning is best for learning python is :
" , str(flag3))
```

## Write a Python Program to Create Random Strings Until a Given String is Generated

You need to write a Python program that will keep generating random combinations of letters and numbers until the desired string is printed. The thing is the string can have a combination of uppercase, lowercase, and special characters.

1. We start by importing all the required modules
2. Then we will declare a variable that will have uppercase letters, lowercase letters, special characters – basically all possible ASCII characters
3. Then you declare the string that you want to get in the end
4. Next step, use a combination of loops and random function to get all possible combinations of ASCII characters
5. Run the loop and set a boolean variable to to True, to match the random strings to the string you want
6. If you get the required string then set the boolean variable to false to stop the loop
7. Then you can use time.sleep() to stop the execution of current thread after the string is matched
8. Lastly, print the iteration after which the string that you wanted was found

Here’s the code!

```# Import required Python modules
import string
import random
import time

# A variable with all possible ASCII characters
allPossibChars = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' ., !?;:'

# declare the string that is to be generated
res_str = "aa"

rand_string1 = ''.join(random.choice(allPossibChars) for i in range(len(res_str)))
rand_stringNext = ''

done= False
iteration = 0

# loops to check the random strings with res_str
while done == False:
print(rand_string1)

rand_stringNext = ''
done = True

# if random string matches with required string
# change the index
for j in range(len(res_str)):
if rand_string1[j] != res_str[j]:
done = False
rand_stringNext += random.choice(allPossibChars)
else:
rand_stringNext += res_str[j]

# increase iteration
iteration += 1
rand_string1 = rand_stringNext
time.sleep(0.1)

print("Target matched after ",iteration," iterations")
```

## Write a Python Program to Find the Words That Are Greater Than Given Length k

The solution is pretty simple. You need to split the given string into a list of substrings and for each substring find the length. Then compare the length of each substring to the variable k. If its greater than k, print the respective string.

```def word_gre_k(k, string):
# split the string where there is white space
word = string.split(" ")
# iterate the list for every word
for x in word:
# if length of current item (word) is greater than k
if len(x)>k:
print(x)
k = 3
s ="Python is great"
word_gre_k(k, s)
```

## Write a Python Program to Remove ith Character From the String

There are different ways to achieve this. Let us look at each of these in detail.

Using Loop

```#using for loop and in operator
string =  input('Enter the string : ')
i = int(input('Input the index at which the character is to be removed : '))

res_Str = ""

for index in range(len(string)):
if index != i:
res_Str = res_Str + string[index]

print ("Input string : " + string)
print ("Resulting string : " + res_Str)
```

Using string replace method

```#using string replace method
string =  input('Enter the string : ')
i = int(input('Input the index at which the character is to be removed : '))

res_Str = string.replace(string[i], "", 1)
print ("Input string : " + string)
print ("Resulting string : " + res_Str)
```

Using string slicing operations

```#using string slicing operations
string =  input('Enter the string : ')
i = int(input('Input the index at which the character is to be removed : '))

res_Str = string[:i] +  string[(i+1):]
print ("Input string : " + string)
print ("Resulting string : " + res_Str)
```

## Write a Python Program to Split and Join a String

You can achieve this by creating two custom functions, one to split the string and the other to join the list of substrings. We are using str.split() and str.join() functions.

```#using split and join methods
def split_the_string(string):

# Split the string based on whitespace delimiter
substring_list = string.split(' ')

return substring_list

def join_the_string(substring_list):

# Then join the list of substrings based on '|' delimiter
string1 = '|'.join(substring_list)

return string1

# Driver Code
if __name__ == '__main__':
test_string1 = 'Python is the best'

# Splitting a string
substring_list = split_the_string(test_string1)
print(substring_list)

# Join list of strings into one
res_string = join_the_string(substring_list)
print(res_string)
```

## Write a Python Program to Replace Commas with Whitespace Character in a Given String

You have to write a program that will replace one delimiter with another one.

Using str.replace() method

The syntax is str.replace(old_string, new_string, count), where old_string is the string to be replaced, new_string is the string with which old string has to be replaced, and the count is the number of times old string should be replaced by a new one. If count is not specified all the occurrences of the old string are replaced.

```#Method 1: Using str.replace() + loop
string1 = "Python,is,my,favourite,lanaguage"
print(string1.replace(","," "))
print(string1.replace(","," ", 2))  #only replaces first 2 occurrences
```

## Write a Python Program to Print All the Permutations of a Given String Using an Inbuilt Function

This is an interesting one. If you see the problem, the statement asks you to write a program to print all the permutations of a string using an inbuilt function. So, which inbuilt function would that be? Give it a try!

Python actually provides various inbuilt methods to generate permutations and combinations of a sequence, which in our case is a string. One such method is permutations, for which you need to import the itertools package.

itertools.permutations(iterable, r = None)

The method returns successive permutations of elements in a given iterable of length r. If r is not specified, it takes the default value, which is the length of the iterable, and returns all possible full-length permutations.

Here’s the code!

```#Print all possible permutations of a given string using itertools.permutations()
from itertools import permutations

def allPermuationsPossible(string):

#count is not specified
substring_list = permutations(string)

#to print all permutations
for perm in list(substring_list):
print (''.join(perm))

#Driver code
if __name__ == "__main__":
string =  input('Enter the string : ')
allPermuationsPossible(string)

```

## Write a Python Program to Check For URL as a Substring in a Given String

You need to write a program that will check if the given string has an URL. If yes, then prints the affirmation message along with the URL found. To achieve that we are going to use a new concept called regular expression.

Python provides a module called re that supports regular expressions. Regular expressions are simply a sequence of characters, which you can use to match or find strings (or set of strings), using a syntax that is given in a pattern. We are actually going to use the findall() method, which will find all the matches and return a list of substrings that match the pattern. The scanning or the parsing takes place from left to right and the matching strings are returned in the same order that they are found.

Here we go!

```
# Check for the URL in a given string
import re
def check_for_urls(string):
# findall() has been used
# with valid conditions for urls in string
reg_exp = r"(?i)((?:https?://|wwwd{0,3}[.]|[a-z0-9.-]+[.][a-z]{2,4}/)(?:[^s()<>]+|(([^s()<>]+|(([^s()<>]+)))*))+(?:(([^s()<>]+|(([^s()<>]+)))*)|[^s`!()[]{};:'".,<>?«»“”‘’]))"
urls = re.findall(reg_exp,string)
return [x[0] for x in urls]

# Driver Code
org_string = 'https://www.shiksha.com/online-courses/ you will get to read awsome blog at link / https://www.shiksha.com/online-courses/articles/'
print("Url is :: ", check_for_urls(org_string))
```

That’s it, guys! Hope you have learned a lot of things. However, to master the basics it’s best you practice by taking up some challenging problem statements and trying to write the code. Let us know if you have any queries in the comment section.

Top Trending Tech Articles:
Career Opportunities after BTech | Online Python Compiler | What is Coding | Queue Data Structure | Top Programming Language | Trending DevOps Tools | Highest Paid IT Jobs | Most In Demand IT Skills | Networking Interview Questions | Features of Java | Basic Linux Commands | Amazon Interview Questions

Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.