Python program to split and join a string

Python program to split and join a string

To demonstrate splitting and joining strings in Python, let's create a simple program:

  1. Splitting a String: The split() method is commonly used to divide a string based on a delimiter.

  2. Joining a String: To join a list of strings into a single string, you can use the join() method.

Here's an example:

def main(): # Original string s = "Hello, how are you today?" print(f"Original String: {s}") # Splitting the string based on spaces split_string = s.split() print(f"Splitted String: {split_string}") # Joining the splitted string joined_string = ' '.join(split_string) print(f"Joined String: {joined_string}") if __name__ == "__main__": main() 

When you run the above program, it will output:

Original String: Hello, how are you today? Splitted String: ['Hello,', 'how', 'are', 'you', 'today?'] Joined String: Hello, how are you today? 

You can further customize the split() method by providing a specific delimiter. For instance, using s.split(",") will split the string based on commas. Similarly, for the join() method, you can replace the ' ' with any other character or string to join the elements using that delimiter.


More Tags

subscribe bitstring delimiter android-toast android-videoview network-analysis django-1.9 synchronization git-diff windows-8.1

More Programming Guides

Other Guides

More Programming Examples