Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - String

Split a string and join using hyphen - Python Program

Example 1 :

text = "Python is fun" print("-".join(text.split()))

Output

 
OUTPUT  :
Python-is-fun

Example 2 :

def split_and_join_with_hyphen(input_string): """ Splits a string by spaces and then joins the resulting list of words with hyphens. Args: input_string (str): The string to be processed. Returns: str: The string with spaces replaced by hyphens. """ # Split the input string by spaces words = input_string.split(' ') # Join the list of words with hyphens joined_string = '-'.join(words) return joined_string # Example Usage: original_string = "This is a sample string" processed_string = split_and_join_with_hyphen(original_string) print(f"Original string: {original_string}") print(f"Processed string: {processed_string}") original_string_2 = "Another example with multiple words" processed_string_2 = split_and_join_with_hyphen(original_string_2) print(f"Original string: {original_string_2}") print(f"Processed string: {processed_string_2}")

Output

 
OUTPUT  :
Original string: This is a sample string
Processed string: This-is-a-sample-string
Original string: Another example with multiple words
Processed string: Another-example-with-multiple-words