Removing front and back space characters from Python

Asked 1 years ago, Updated 1 years ago, 76 views

I want to remove the first and last blank characters from the string For example,

" Hello " --> "Hello"
" " Hello"  --> "Hello"
"Hello "  --> "Hello"
"Bob has a cat" --> "Bob has a cat"

Like this.

string python trim

2022-09-21 15:13

1 Answers

Do you want to remove only one space character or multiple spaces?

def strip_one(s):
    Ifs.endswith("): s = s[:-1] #Check that the last is ""
    If s.startswith("): s = s[1:] #Check that the first is ""
    return s
a = "  hello  "
print strip_one(a)

str.strip([chars])은 스트링 맨앞/뒤의 chars를 찾아 제거합니다. chars를 지정하지 않은 경우 모든 종류의 공백 문자를 제거하니 " "만 제거하고 싶다면 strip(" ")과 같이 사용하세요.

a = "   hello\nworld\n"

print "--strip(' ') start---"
print a.strip(" ")
print "---------end---------"
print "----strip() start----"
print a.strip()
print "---------end---------"

Results are

--strip(' ') start---
hello
world

---------end---------
----strip() start----
hello
world
---------end---------


2022-09-21 15:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.