How to Split and Join a String in Python
In this tutorial, we will program "How to Split and Join a String in the Console Terminal using Python." We’ll focus on splitting a string into segments and then rejoining it with a specified character or string. The objective is to split a given string safely and then join it with an additional character or separator to form a new string. A sample program will be provided to demonstrate the coding process.
This topic is straightforward to understand. Just follow the instructions I provide, and you'll be able to complete it yourself with ease. The program I'll show you demonstrates the correct way to split a string and then join it using a specific character. I'll also provide a simple and efficient method to achieve this effectively. So, let’s start coding!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- import re
- def split_string(string):
- list_string = re.split('\s+', string)
- return list_string
- def join_string(list_string):
- new_string = '-'.join(list_string)
- return new_string
- if __name__ == '__main__':
- while True:
- print("\n================= Split and Join a String =================\n\n")
- string = input("Enter a String: ")
- list_string = split_string(string)
- print(list_string)
- new_string = join_string(list_string)
- print(new_string)
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- continue
This code allows users to input a string, which it then splits into a list of words using whitespace as the delimiter. After that, it joins the list of words into a new string with hyphens between each word. The program continues to prompt the user for new strings and performs the same operations until the user decides to exit by entering "no."
Output:
There you have it we successfully created How to Split and Join a String in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language
Add new comment
- 37 views