[Python!] - String.split() & max(str, key=len)

xxhaileypark·2021년 11월 12일
0

Python!

목록 보기
8/11
post-thumbnail

위코드 중간시험

Q3.

"get_prefix" 함수를 작성하세요.
문자열이 주어졌을때, “-”를 기준으로 앞에 있는 문자열을 반환하세요.

print(get_prefix('BTC-KRW')) # --> BTC

A.

def get_prefix(str):
	return str.split("-")[0] 

We can split string using split().
Syntax is as below.

string.split(separator, maxsplit)
  • seperator : This seperator splits the string. The default is whitespace.

  • maxsplit : The number of times to split. The default is -1, which means split string unlimited number of times.

1st e.g.

text = 'Hello world, python'
strings = text.split()
print(strings)

OUTPUT:

['Hello', 'world,', 'python']

2nd e.g.

text = 'Hello, world, python'
strings = text.split(',', 0)
print(strings)

OUTPUT:

['Hello, world, python']

3rd e.g.

text = 'Hello, world, python'
strings = text.split(',', 1)
print(strings)

OUTPUT:

['Hello', ' world, python']

4th e.g.

text = 'Hello, world, python'
strings = text.split(',', -1)
print(strings)

OUTPUT:

['Hello', ' world', ' python']

Q5.

주어진 리스트안에 있는 단어중 가장 긴 단어를 찾을수 있도록 함수를 완성해주세요.

print(find_longest_word(["PHP", "Exercises", "Backend"])) # --> "Exercises"

A.

def find_longest_word(words):
	return max(words, key=len) 

Use Python’s built-in max() function with a key argument to find the longest string in a list. Call max(lst, key=len) to return the longest string in lst using the built-in len() function to associate the weight of each string—the longest string will be the maximum.

Here’s the code definition of the get_max_str() function that takes a list of strings as input and returns the longest string in the list or a ValueError if the list is empty.

def get_max_str(lst):
    return max(lst, key=len)

Here’s the output on our desired examples:

print(get_max_str(['Alice', 'Bob', 'Pete']))
# 'Alice'
print(get_max_str(['aaa', 'aaaa', 'aa']))
# 'aaaa'
print(get_max_str(['']))
# ''
print(get_max_str([]))
# ValueError

If you want to return an alternative value in case the list is empty, you can modify the get_max_str() function to include a second optional argument:

def get_max_str(lst, fallback=''):
    return max(lst, key=len) if lst else fallback
print(get_max_str([]))
# ''
print(get_max_str([], fallback='NOOOOOOOOO!!!!!!'))
# NOOOOOOOOO!!!!!!
profile
I'm a deeply superficial person.

0개의 댓글