Programming/Python
[Python/Hackerrank] Strings > String Split and Join
hoojiv
2021. 12. 8. 14:09
728x90
String Split and Join
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
문제해석
입력받은 문자열에서 " " 공백을 - 하이픈으로 변경하여 출력한다.
문제풀이
개인적으로 Basic Data Types 코스는 너무 어려웠는데... Strings가 먼저 나오는게 맞지 않나 싶다...;
문제에서 split은 문자열을 분리하는 함수이고 join은 다시 합칠 수 있는 함수라고 설명해 주었으므로,
split(" ")함수를 사용하여 문자열을 분리한 후 '-'.join()하면 - 하이픈으로 구분하여 다시 합칠 수 있다.
def split_and_join(line):
# write your code here
return '-'.join(line.split(" "))
if __name__ == '__main__':
line = raw_input()
result = split_and_join(line)
print result
728x90
LIST