파이썬에서 문자열 끝에서 공백을 어떻게 제거합니까?


93

문자열에서 단어 뒤의 공백을 제거해야합니다. 한 줄의 코드로이 작업을 수행 할 수 있습니까?

예:

string = "    xyz     "

desired result : "    xyz" 

3
이 질문이 정말 여기에서 물어봐야 했나요? 문서에서 쉽게 찾을 수 있습니다. docs.python.org/library/stdtypes.html#str.rstrip
Greg K

11
@Greg K 예, 문서를 읽은 사람조차도 문서가 있다는 것을 깨닫지 못할 수 있습니다. 처음 몇 번 읽었을 수 있다는 것이 근본적인 것으로 생각하고 관련없는 말로 기억합니다. 또한 문서의 rstrip은이 문제에 대한 Google 검색에서 쉽게 표시되지 않습니다 ( 'python strip end of string'기준 사용).
Brōtsyorfuzthrāx

4
실제 감기는 실제 감기 @GregK
deepelement

답변:



1

strip () 또는 split ()을 사용하여 다음과 같이 공백 값을 제어 할 수 있습니다.

words = "   first  second   "

# remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())


# remove first and end spaces
def remove_first_end_spaces(string):
    return "".join(string.rstrip().lstrip())


# remove all spaces
def remove_all_spaces(string):
    return "".join(string.split())

print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))

도움이 되었기를 바랍니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.