write a python program that takes a list of strings as input and outputs a new list containing the first three characters of each string

Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Program That Takes A List Of Strings As Input And Outputs A New List Containing The First Three Characters Of Each String

 

Title : 

Write A Python Program That Takes A List Of Strings As Input And Outputs A New List Containing The First Three Characters Of Each String



Write A Python Program That Takes A List Of Strings As Input And Outputs A New List Containing The First Three Characters Of Each String


 

Description : 

Hi guys, in this article you will learn a python program that generates a new list of strings containing the first 3 letters of each string of the input list. Your task is to create a list of strings containing the first 3 letters of the input string. Take a length variable and ask the user to enter a list length. Keep iterating until this length and as a user to enter strings inside the list and append it to the list.


    
length = int(input("Enter Number of Strings : "))
strings = []
for _ in range(length):
   string = input("Enter a String : ")
   strings.append(string)


    


Take a new list of strings and use a for loop to iterate all the strings present in the list. Use the string slicing method to only get the first three characters out of each string and append it to the output list. Use the print function call to print the new output list


    
new_strings = []
for string in strings:
   new_strings.append(string[:3])

print("The new list of strings containing the first three characters is ..")
print(new_strings)


    




Complete Python Code : 


    
length = int(input("Enter Number of Strings : "))
strings = []
for _ in range(length):
   string = input("Enter a String : ")
   strings.append(string)

new_strings = []
for string in strings:
   new_strings.append(string[:3])

print("The new list of strings containing the first three characters is ..")
print(new_strings)


    

 

 

Output : 


    
Enter Number of Strings : 2
Enter a String : hello
Enter a String : world
The new list of strings containing the first three characters is ..
['hel', 'wor']


    

 

Output : 


    
Enter Number of Strings : 3
Enter a String : code
Enter a String : with
Enter a String : tj
The new list of strings containing the first three characters is ..
['cod', 'wit', 'tj']


    



Conclusion :

The above Python program asks the user to enter the list of strings and then uses string slicing method to create a new list of strings. The new list of strings will contain the first three characters of the input list of strings. Comment it down below if you have any suggestions to improve the above Python program

 

Post a Comment

0 Comments