띄어쓰기/탭/새 선 - python
리눅스의 python 2.7에서 모든 spaces/tabs/newline을 제거하려고 합니다.
제가 쓴 건데, 그렇게 하면 될 겁니다.
myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
myString = myString.strip(' \n\t')
print myString
출력:
I want to Remove all white spaces, new lines
and tabs
간단한 일인 것 같지만, 저는 여기서 무언가를 놓치고 있습니다.제가 뭔가를 수입해야 하나요?
사용하다str.split([sep[, maxsplit]])무일푼으로sep아니면sep=None:
문서에서:
한다면
sep지정되지 않았거나 다음과 같습니다.None, 다른 분할 알고리즘이 적용됩니다. 연속된 공백의 실행은 단일 구분자로 간주되며 문자열에 선두 또는 후행 공백이 있는 경우 시작 또는 끝에 빈 문자열이 포함되지 않습니다.
데모:
>>> myString.split()
['I', 'want', 'to', 'Remove', 'all', 'white', 'spaces,', 'new', 'lines', 'and', 'tabs']
사용하다str.join다음 출력을 얻기 위해 반환된 목록에서:
>>> ' '.join(myString.split())
'I want to Remove all white spaces, new lines and tabs'
여러 공백 항목을 제거하고 단일 공백으로 바꾸려면 다음과 같은 regexp를 사용하는 것이 가장 쉬운 방법입니다.
>>> import re
>>> myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
>>> re.sub('\s+',' ',myString)
'I want to Remove all white spaces, new lines and tabs '
그런 다음 후행 공간을 제거할 수 있습니다..strip()원하신다면
거기서 라이브러리를 사용합니다.
import re
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
myString = re.sub(r"[\n\t\s]*", "", myString)
print myString
출력:
공백, 새 줄 및 탭을 모두 제거합니다.
이렇게 하면 탭, 새 줄, 공백만 제거되고 다른 항목은 제거되지 않습니다.
import re
myString = "I want to Remove all white \t spaces, new lines \n and tabs \t"
output = re.sub(r"[\n\t\s]*", "", myString)
출력:
모든 와이스페이스, 새 줄, 탭을 제거하고 싶습니다.
좋은 하루!
import re
mystr = "I want to Remove all white \t spaces, new lines \n and tabs \t"
print re.sub(r"\W", "", mystr)
Output : IwanttoRemoveallwhitespacesnewlinesandtabs
regex의 사용을 제안하는 위의 솔루션은 매우 작은 작업이며 regex는 작업의 단순성이 정당화하는 것보다 더 많은 리소스 오버헤드를 필요로 하기 때문에 이상적이지 않습니다.
제가 하는 일은 이렇습니다.
myString = myString.replace(' ', '').replace('\t', '').replace('\n', '')
한 줄의 용액이 쓸데없이 길어질 정도로 제거해야 할 것이 많다면:
removal_list = [' ', '\t', '\n']
for s in removal_list:
myString = myString.replace(s, '')
조인 내에서 리스트 이해를 사용하는 원라이너는 어떻습니까?
>>> foobar = "aaa bbb\t\t\tccc\nddd"
>>> print(foobar)
aaa bbb ccc
ddd
>>> print(''.join([c for c in foobar if c not in [' ', '\t', '\n']]))
aaabbbcccddd
그 외에 더 복잡한 것이 없기 때문에, 저는 그것이 저에게 도움이 되었습니다.
이것은 제가 원래 사용했던 것입니다.
import requests
import re
url = 'https://stackoverflow.com/questions/10711116/strip-spaces-tabs-newlines-python' # noqa
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
print("{}".format(r.content))
원하지 않는 결과:
b'<!DOCTYPE html>\r\n\r\n\r\n <html itemscope itemtype="http://schema.org/QAPage" class="html__responsive">\r\n\r\n <head>\r\n\r\n <title>string - Strip spaces/tabs/newlines - python - Stack Overflow</title>\r\n <link
이렇게 변경했습니다.
import requests
import re
url = 'https://stackoverflow.com/questions/10711116/strip-spaces-tabs-newlines-python' # noqa
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
regex = r'\s+'
print("CNT: {}".format(re.sub(regex, " ", r.content.decode('utf-8'))))
원하는 결과:
<!DOCTYPE html> <html itemscope itemtype="http://schema.org/QAPage" class="html__responsive"> <head> <title>string - Strip spaces/tabs/newlines - python - Stack Overflow</title>
@MattH가 언급한 정확한 정규군이 제 코드에 맞는 데 도움이 되었습니다.감사합니다!
참고: 이것은python3
언급URL : https://stackoverflow.com/questions/10711116/strip-spaces-tabs-newlines-python
'programing' 카테고리의 다른 글
| 어떻게 하면 중앙에 유연한 기둥이 하나 있는 고정 폭 기둥 두 개를 가질 수 있습니까? (0) | 2023.09.21 |
|---|---|
| UIAapplication.registerForRemoteNotifications()는 기본 스레드에서만 호출해야 합니다. (0) | 2023.09.21 |
| Github에서 프로젝트의 라이센스를 변경하는 방법은? (0) | 2023.09.21 |
| dataType json의 jQuery $.ajax 요청이 PHP 스크립트에서 데이터를 검색하지 않습니다. (0) | 2023.09.21 |
| PHP를 사용하여 데이터베이스에서 반복하지 않고 난수를 생성하는 방법? (0) | 2023.09.21 |