문자열에서 공백(공백 및 탭)을 잘라내는 Python 함수가 있나요?
예: \t 예제 문자열\t
→ 예제 문자열
양쪽에 공백이 있습니다:
s = " \t a string example\t "
s = s.strip()
오른쪽에 공백이 있습니다:
s = s.rstrip()
왼쪽의 공백:
s = s.lstrip()
thedz]1이 지적한 것처럼, 이러한 함수에 임의의 문자를 제거하도록 인수를 제공할 수 있습니다:
s = s.strip(' \t\n\r')
이렇게 하면 문자열의 왼쪽, 오른쪽 또는 양쪽에서 공백, \t
, \n
또는 \r
문자가 모두 제거됩니다.
위의 예는 문자열의 왼쪽과 오른쪽에서만 문자열을 제거합니다. 문자열 가운데의 문자도 제거하려면 re.sub
를 사용해 보세요:
import re
print re.sub('[\s+]', '', s)
그러면 출력됩니다:
astringexample
아주 간단한, 기본 기능을 사용할 수도 있습니다. [1], [스트라이어플레이스 ()] 와 연동하여 공백 및 탭들:
>>> whitespaces = " abcd ef gh ijkl "
>>> tabs = " abcde fgh ijkl"
>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl
쉽고 간단한. [1]: https://docs.python.org/2/library/stdtypes.html # 스트라이어플레이스
#how to trim a multi line string or a file
s=""" line one
\tline two\t
line three """
#line1 starts with a space, #2 starts and ends with a tab, #3 ends with a space.
s1=s.splitlines()
print s1
[' line one', '\tline two\t', 'line three ']
print [i.strip() for i in s1]
['line one', 'line two', 'line three']
#more details:
#we could also have used a forloop from the begining:
for line in s.splitlines():
line=line.strip()
process(line)
#we could also be reading a file line by line.. e.g. my_file=open(filename), or with open(filename) as myfile:
for line in my_file:
line=line.strip()
process(line)
#moot point: note splitlines() removed the newline characters, we can keep them by passing True:
#although split() will then remove them anyway..
s2=s.splitlines(True)
print s2
[' line one\n', '\tline two\t\n', 'line three ']
Regex 올렸다고 솔루션뀉뀉뀉뀉 아직 없다.
일치:
>>> import re
>>> p=re.compile('\\s*(.*\\S)?\\s*')
>>> m=p.match(' \t blah ')
>>> m.group(1)
'blah'
>>> m=p.match(' \tbl ah \t ')
>>> m.group(1)
'bl ah'
>>> m=p.match(' \t ')
>>> print m.group(1)
None
검색: (, 단지 spaces" " 처리할 수 있습니다. 입력입니다 경우 다르게):
>>> p1=re.compile('\\S.*\\S')
>>> m=p1.search(' \tblah \t ')
>>> m.group()
'blah'
>>> m=p1.search(' \tbl ah \t ')
>>> m.group()
'bl ah'
>>> m=p1.search(' \t ')
>>> m.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
'공백' 레오서브 사용하는 경우, 내부 제거할 수 있습니다 수 있는 것은 바람직하지 않다고 말했습니다.
>. (레오서브 (& # 39. # 39, & # 39 +&;; & # 39, (my_str.replace (& # 39, & # 39 \n& # 39;; & # 39;)))) 오스트리프 ()
원하지 않는 공간 및 개행 문자를 모두 제거됩니다. ᄋ "이번 도움말에서는
import re
my_str = ' a b \n c '
formatted_str = (re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()
이렇게 하면:
& # 39. 빨리, 빨리, 빨리, 빨리 한 & & & &;;;; b, c & # 39 \n , b c& # 39 & # 39 로 바뀐다.
파이썬 사용하는 경우 3: 성명을 통해, 9월 = " " in your 인쇄하십시오 스크립트종료;. 모든 구분하는 아웃해야 독창적이다.
예:
txt="potatoes"
print("I love ",txt,"",sep="")
이렇게 print:* I love 감자여.
대신 of:* I love 감자여.
이후 이 \t 탈 수 있는 경우, 당신이 약간만이라도 얻으려고 하고 9월 = " 확신하느뇨 \t";
변환하기에 시도하시겠습니까
>>> import string
>>> print '\t\r\n hello \r\n world \t\r\n'
hello
world
>>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr)
' hello world '
>>> '\t\r\n hello \r\n world \t\r\n'.translate(tr).replace(' ', '')
'helloworld'
그냥 공백 오프하도록 확인표시를 트림하려면 시작과 끝을 문자열이어야 이 같은 일이 수행할 수 있습니다.
some_string = " Hello, world!\n "
new_string = some_string.strip()
# new_string is now "Hello, world!"
some_string = "\t Hello, \n\t world!\n "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"
예를 들어, 이 마지막 한 번의 내부 공간, 동시에 각 조합으 공백을 재장착하여 공백을 트리밍할 끕니까 시작과 끝을 구체화하십시오.
일반적으로 다음과 같은 방법을 사용하여, 나는.
>>> myStr = "Hi\n Stack Over \r flow!"
>>> charList = [u"\u005Cn",u"\u005Cr",u"\u005Ct"]
>>> import re
>>> for i in charList:
myStr = re.sub(i, r"", myStr)
>>> myStr
'Hi Stack Over flow'
참고: 이것은 단지 ";;, " 제거하기 위한 \n" \r". 및 " \t"; 뿐입니다. 공백 제거되지는 않습니다.
공백 가운데 문자열의 제거
$p = "ATGCGAC ACGATCGACC";
$p =~ s/\s//g;
print $p;
출력:
ATGCGACACGATCGACC