HackerRank Python: String Split and Join Solution

Table of Contents

Question

In Python, a string can be split on a delimiter.

Example:

>>> a = "this is a string"
>>> a = a.split(" ") # a is converted to a list of strings. 
>>> print a
['this', 'is', 'a', 'string']

Joining a string is simple:

>>> a = "-".join(a)
>>> print a
this-is-a-string 

Task
You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen.

Function Description

Complete the split_and_join function in the editor below.

split_and_join has the following parameters:

  • string line: a string of space-separated words

Returns

  • string: the resulting string

Input Format
The one line contains a string consisting of space separated words.

Sample Input

this is a string   

Sample Output

this-is-a-string

Solution

				
					def split_and_join(line):
    words = line.split()  # Split the line into a list of words using the space delimiter
    joined_string = "-".join(words)  # Join the words using the hyphen delimiter
    return joined_string

# Read the input line
line = input()

# Call the split_and_join function and print the result
result = split_and_join(line)
print(result)

				
			
  1. We define a function called split_and_join that takes a string line as input.
  2. Inside the function, we split the input string into a list of words using the split() method with no arguments. By default, split() splits the string on whitespace characters (spaces, tabs, newlines) and returns a list of the resulting words.
  3. We then join the words in the list using the join() method, specifying the hyphen as the delimiter between the words. This creates a new string where the words are joined by hyphens.
  4. The resulting joined string is returned from the function.
  5. In the main part of the code, we read the input line using the input() function.
  6. We call the split_and_join function with the input line as an argument and store the returned result in the variable result.
  7. Finally, we print the value of result, which is the modified string with the words joined by hyphens instead of spaces.
  8.  

If you find anything wrong in this Solution, feel free to reach us in the comment section.

Sharing Is Caring:

Leave a Comment