Program Tip

공백을 제거하려면 어떻게합니까?

programtip 2020. 9. 27. 13:48
반응형

공백을 제거하려면 어떻게합니까?


문자열에서 공백 (공백 및 탭)을 제거하는 Python 함수가 있습니까?

예 : \t example string\texample string


양쪽에 공백 :

s = "  \t a string example\t  "
s = s.strip()

오른쪽의 공백 :

s = s.rstrip()

왼쪽의 공백 :

s = s.lstrip()

으로 thedz는 지적,이 같은 이러한 기능 중 하나에 임의의 문자를 제거하기 위해 인수를 제공 할 수 있습니다 :

s = s.strip(' \t\n\r')

이 모든 공간을 제거합니다, \t, \n, 또는 \r왼쪽의 문자, 오른쪽, 또는 문자열의 양쪽.

위의 예는 문자열의 왼쪽과 오른쪽에서만 문자열을 제거합니다. 문자열 중간에서 문자를 제거하려면 re.sub다음을 시도하십시오 .

import re
print re.sub('[\s+]', '', s)

다음과 같이 출력되어야합니다.

astringexample

Python trim메서드가 호출됩니다 strip.

str.strip() #trim
str.lstrip() #ltrim
str.rstrip() #rtrim

선행 및 후행 공백의 경우 :

s = '   foo    \t   '
print s.strip() # prints "foo"

그렇지 않으면 정규식이 작동합니다.

import re
pat = re.compile(r'\s+')
s = '  \t  foo   \t   bar \t  '
print pat.sub('', s) # prints "foobar"

매우 간단하고 기본적인 함수 인 str.replace () 를 사용할 수도 있으며 공백과 탭과 함께 작동합니다.

>>> whitespaces = "   abcd ef gh ijkl       "
>>> tabs = "        abcde       fgh        ijkl"

>>> print whitespaces.replace(" ", "")
abcdefghijkl
>>> print tabs.replace(" ", "")
abcdefghijkl

간단하고 쉽습니다.


#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 ']

아직 아무도 이러한 정규식 솔루션을 게시하지 않았습니다.

어울리는:

>>> 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

검색 ( "공백 만"입력 사례를 다르게 처리해야 함) :

>>> 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'

를 사용 re.sub하면 내부 공백을 제거 할 수 있으며 이는 바람직하지 않을 수 있습니다.


공백에는 공백, 탭 및 CRLF가 포함 됩니다. 따라서 우리가 사용할 수 있는 우아하고 한 줄짜리 문자열 함수는 translate 입니다.

' hello apple'.translate(None, ' \n\t\r')

또는 철저히하고 싶다면

import string
' hello  apple'.translate(None, string.whitespace)

(re.sub ( '+', '', (my_str.replace ( '\ n', '')))). strip ()

이렇게하면 원치 않는 모든 공백과 개행 문자가 제거됩니다. 이 도움을 바랍니다

import re
my_str = '   a     b \n c   '
formatted_str = (re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()

결과는 다음과 같습니다.

' a      b \n c ' will be changed to 'a b c'


    something = "\t  please_     \t remove_  all_    \n\n\n\nwhitespaces\n\t  "

    something = "".join(something.split())

output: please_remove_all_whitespaces


If using Python 3: In your print statement, finish with sep="". That will separate out all of the spaces.

EXAMPLE:

txt="potatoes"
print("I love ",txt,"",sep="")

This will print: I love potatoes.

Instead of: I love potatoes .

In your case, since you would be trying to get ride of the \t, do sep="\t"


try translate

>>> 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'

If you want to trim the whitespace off just the beginning and end of the string, you can do something like this:

some_string = "    Hello,    world!\n    "
new_string = some_string.strip()
# new_string is now "Hello,    world!"

This works a lot like Qt's QString::trimmed() method, in that it removes leading and trailing whitespace, while leaving internal whitespace alone.

But if you'd like something like Qt's QString::simplified() method which not only removes leading and trailing whitespace, but also "squishes" all consecutive internal whitespace to one space character, you can use a combination of .split() and " ".join, like this:

some_string = "\t    Hello,  \n\t  world!\n    "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"

In this last example, each sequence of internal whitespace replaced with a single space, while still trimming the whitespace off the start and end of the string.


Generally, I am using the following method:

>>> 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'

Note: This is only for removing "\n", "\r" and "\t" only. It does not remove extra spaces.


for removing whitespaces from the middle of the string

$p = "ATGCGAC ACGATCGACC";
$p =~ s/\s//g;
print $p;

output:

ATGCGACACGATCGACC

This will remove all whitespace and newlines from both the beginning and end of a string:

>>> s = "  \n\t  \n   some \n text \n     "
>>> re.sub("^\s+|\s+$", "", s)
>>> "some \n text"

참고URL : https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace

반응형