split2 [LeetCode] Number of Segments in a String 파이썬 (white space as None) class Solution: def countSegments(self, s: str) -> int: return len([i for i in s.strip().split(' ') if i]) strip은 안전하게 양쪽 끝의 공백을 제거하는 용도로 넣어준 듯. if i 라는 조건을 통해 whitespace가 아닐 경우만 새로운 list의 원소로 추가. str.strip str.strip([chars]) Return a copy of the string with the leading and trailing characters removed. 2021. 4. 16. [LeetCode] Length of Last Word 파이썬 (rstrip, split) class Solution: def lengthOfLastWord(self, s): return len(s.rstrip(' ').split(' ')[-1]) 문제에 잘 설명이 안되어 있어서 그런지 downvote가 3천개 s = "a "이 경우에서 wrong answer가 발생하는 거에서 막혔는데 내가 생각했을때는 0이 맞다고 보는데 1로 return 해야된다고 하니 문제에서 last word라고 한것은 제일 오른쪽 끝에 공백이 있으면 그 바로 전 word의 length를 return 하는 것으로 요구한듯. 아무튼 여기서 가져갈 것은 strip을 사용하는 것. 2021. 3. 30. 이전 1 다음