IT

문자열에서 모든 공백을 제거하는 방법

lottoking 2020. 5. 31. 10:32
반응형

문자열에서 모든 공백을 제거하는 방법


파이썬 문자열의 모든 공백을 어떻게 제거합니까? 예를 들어, 문자열 strip my spaces을로 바꾸고 stripmyspaces싶지만 strip()다음 같이 달성 할 수는 없습니다 .

>>> 'strip my spaces'.strip()
'strip my spaces'

sep 매개 변수없이 str.split의 동작 활용 :

>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'

모든 공백 대신 공백을 제거하려는 경우 :

>>> s.replace(" ", "")
'\tfoo\nbar'

조기 최적화

명확한 코드를 작성하는 것이 효율성이 주요 목표는 아니지만 초기 타이밍은 다음과 같습니다.

$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop

정규식이 캐시되어 있으므로 예상보다 느리지 않습니다. 미리 컴파일하면 도움이 될 수 있지만 여러호출하면 실제로 중요합니다 .

$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop

re.sub의 속도는 11.3 배 더 느리지 만 병목 현상은 다른 곳에서도 확실하게 기억하십시오. 대부분의 프로그램은이 3 가지 선택의 차이점을 인식하지 못합니다.


>>> import re
>>> re.sub(r'\s+', '', 'strip my spaces')
'stripmyspaces'

또한 당신이 생각하지 않는 공백 문자를 처리합니다 (믿습니다. 많이 있습니다).


또는

"strip my spaces".translate( None, string.whitespace )

그리고 여기에 Python3 버전이 있습니다 :

"strip my spaces".translate(str.maketrans('', '', string.whitespace))

가장 간단한 방법은 replace를 사용하는 것입니다.

"foo bar\t".replace(" ", "").replace("\t", "")

또는 정규식을 사용하십시오.

import re
re.sub(r"\s", "", "foo bar\t")

파이썬에서 시작 공간 제거

string1="    This is Test String to strip leading space"
print string1
print string1.lstrip()

파이썬에서 후행 또는 끝 공간 제거

string2="This is Test String to strip trailing space     "
print string2
print string2.rstrip()

파이썬에서 문자열의 시작과 끝에서 공백을 제거하십시오.

string3="    This is Test String to strip leading and trailing space      "
print string3
print string3.strip()

파이썬에서 모든 공백을 제거하십시오

string4="   This is Test String to test all the spaces        "
print string4
print string4.replace(" ", "")

로 정규식을 사용해보십시오 re.sub. 모든 공백을 검색하고 빈 문자열로 바꿀 수 있습니다.

\s패턴에서 공백 (탭, 줄 바꿈 등)뿐만 아니라 공백 문자와 일치합니다. 자세한 내용 은 설명서를 참조하십시오 .


import re
re.sub(' ','','strip my spaces')

Roger Pate가 언급했듯이 다음 코드가 나를 위해 일했습니다.

s = " \t foo \n bar "
"".join(s.split())
'foobar'

Jupyter Notebook을 사용하여 다음 코드를 실행하고 있습니다.

i=0
ProductList=[]
while i < len(new_list): 
   temp=''                            # new_list[i]=temp=' Plain   Utthapam  '
   #temp=new_list[i].strip()          #if we want o/p as: 'Plain Utthapam'
   temp="".join(new_list[i].split())  #o/p: 'PlainUtthapam' 
   temp=temp.upper()                  #o/p:'PLAINUTTHAPAM' 
   ProductList.append(temp)
   i=i+2

The standard techniques to filter a list apply, although they are not as efficient as the split/join or translate methods.

We need a set of whitespaces:

>>> import string
>>> ws = set(string.whitespace)

The filter builtin:

>>> "".join(filter(lambda c: c not in ws, "strip my spaces"))
'stripmyspaces'

A list comprehension (yes, use the brackets: see benchmark below):

>>> import string
>>> "".join([c for c in "strip my spaces" if c not in ws])
'stripmyspaces'

A fold:

>>> import functools
>>> "".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))
'stripmyspaces'

Benchmark:

>>> from timeit import timeit
>>> timeit('"".join("strip my spaces".split())')
0.17734256500003198
>>> timeit('"strip my spaces".translate(ws_dict)', 'import string; ws_dict = {ord(ws):None for ws in string.whitespace}')
0.457635745999994
>>> timeit('re.sub(r"\s+", "", "strip my spaces")', 'import re')
1.017787621000025

>>> SETUP = 'import string, operator, functools, itertools; ws = set(string.whitespace)'
>>> timeit('"".join([c for c in "strip my spaces" if c not in ws])', SETUP)
0.6484303600000203
>>> timeit('"".join(c for c in "strip my spaces" if c not in ws)', SETUP)
0.950212219999969
>>> timeit('"".join(filter(lambda c: c not in ws, "strip my spaces"))', SETUP)
1.3164566040000523
>>> timeit('"".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))', SETUP)
1.6947649049999995

TL/DR

This solution was tested using Python 3.6

To strip all spaces from a string in Python3 you can use the following function:

def remove_spaces(in_string: str):
    return in_string.translate(str.maketrans({' ': ''})

To remove any whitespace characters (' \t\n\r\x0b\x0c') you can use the following function:

import string
def remove_whitespace(in_string: str):
    return in_string.translate(str.maketrans(dict.fromkeys(string.whitespace)))

Explanation

Python's str.translate method is a built-in class method of str, it takes a table and returns a copy of the string with each character mapped through the passed translation table. Full documentation for str.translate

To create the translation table str.maketrans is used. This method is another built-in class method of str. Here we use it with only one parameter, in this case a dictionary, where the keys are the characters to be replaced mapped to values with the characters replacement value. It returns a translation table for use with str.translate. Full documentation for str.maketrans

The string module in python contains some common string operations and constants. string.whitespace is a constant which returns a string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.Full documentation for string

In the second function dict.fromkeys is used to create a dictionary where the keys are the characters in the string returned by string.whitespace each with value None. Full documentation for dict.fromkeys

참고URL : https://stackoverflow.com/questions/3739909/how-to-strip-all-whitespace-from-string

반응형