백엔드 개발 파이썬 튜토리얼 python编程开发之textwrap文本样式处理技巧

python编程开发之textwrap文本样式处理技巧

Jun 10, 2016 pm 03:07 PM
python 프로그래밍 개발

本文实例讲述了python编程开发之textwrap文本样式处理技巧。分享给大家供大家参考,具体如下:

在看python的API的时候,发现python的textwrap在处理字符串样式的时候功能强大

在这里我做了一个demo:

textwrap提供了一些方法:

wrap(text, width = 70, **kwargs):这个函数可以把一个字符串拆分成一个序列

from textwrap import *
#使用textwrap中的wrap()方法
def test_wrap():
  test_str = '''\
  The textwrap module provides two convenience functions, wrap() and fill(), as well as 1
  TextWrapper, the class that does all the work, and two utility functions, dedent() and indent(). If 2
  you're just wrapping or filling one or two text strings, the convenience functions should be good 3
  enough; otherwise, you should use an instance of TextWrapper for efficiency. 4
  '''
  print(wrap(test_str, 20))
def main():
  test_wrap()
if __name__ == '__main__':
  main()

로그인 후 복사

输出效果:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
['  The textwrap', 'module provides two', 'convenience', 'functions, wrap()', 'and fill(), as well', 'as 1', 'TextWrapper, the', 'class that does all', 'the work, and two', 'utility functions,', 'dedent() and', 'indent(). If 2', 'you're just wrapping', 'or filling one or', 'two text strings,', 'the convenience', 'functions should be', 'good 3   enough;', 'otherwise, you', 'should use an', 'instance of', 'TextWrapper for', 'efficiency. 4']
>>>

로그인 후 복사

我们会发现,wrap()函数,把字符串拆分成了一个序列,在这个序列中,每个元素的长度是一样的。

fill(text, width=70, **kwargs) :该方法可以根据指定的长度,进行拆分字符串,然后逐行显示

from textwrap import *
#fill()方法
def test_wrap():
  test_str = '''\
  The textwrap module provides two convenience functions, wrap() and fill(), as well as 1
  TextWrapper, the class that does all the work, and two utility functions, dedent() and indent(). If 2
  you're just wrapping or filling one or two text strings, the convenience functions should be good 3
  enough; otherwise, you should use an instance of TextWrapper for efficiency. 4
  '''
  print(fill(test_str, 40))
def main():
  test_wrap()
if __name__ == '__main__':
  main()

로그인 후 복사

运行效果:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
  The textwrap module provides two
convenience functions, wrap() and
fill(), as well as 1   TextWrapper,
the class that does all the work, and
two utility functions, dedent() and
indent(). If 2   you're just wrapping
or filling one or two text strings, the
convenience functions should be good 3
enough; otherwise, you should use an
instance of TextWrapper for efficiency.
>>>

로그인 후 복사

dedent()方法->文本进行不缩进显示,相应的indent()方法 -> 进行缩进显示

from textwrap import *
#dedent()方法
def test_wrap():
  test_str = '''\
  The textwrap module provides two convenience
    functions, wrap() and fill(), as well as 1
  TextWrapper, the class that does all the work,
    and two utility functions, dedent() and indent(). If 2
  you're just wrapping or filling one or two text strings,
    the convenience functions should be good 3
  enough; otherwise, you should use an instance
    of TextWrapper for efficiency. 4
  '''
  print(repr(dedent(test_str)))
def main():
  test_wrap()
if __name__ == '__main__':
  main()

로그인 후 복사

运行效果:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
'The textwrap module provides two convenience\n  functions, wrap() and fill(), as well as 1\nTextWrapper, the class that does all the work,\n  and two utility functions, dedent() and indent(). If 2\nyou're just wrapping or filling one or two text strings,\n  the convenience functions should be good 3\nenough; otherwise, you should use an instance\n  of TextWrapper for efficiency. 4\n'
>>>

로그인 후 복사

希望本文所述对大家Python程序设计有所帮助。

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Linux 터미널에서 Python 버전을 볼 때 발생하는 권한 문제를 해결하는 방법은 무엇입니까? Apr 01, 2025 pm 05:09 PM

Linux 터미널에서 Python 버전을 보려고 할 때 Linux 터미널에서 Python 버전을 볼 때 권한 문제에 대한 솔루션 ... Python을 입력하십시오 ...

한 데이터 프레임의 전체 열을 Python의 다른 구조를 가진 다른 데이터 프레임에 효율적으로 복사하는 방법은 무엇입니까? 한 데이터 프레임의 전체 열을 Python의 다른 구조를 가진 다른 데이터 프레임에 효율적으로 복사하는 방법은 무엇입니까? Apr 01, 2025 pm 11:15 PM

Python의 Pandas 라이브러리를 사용할 때는 구조가 다른 두 데이터 프레임 사이에서 전체 열을 복사하는 방법이 일반적인 문제입니다. 두 개의 dats가 있다고 가정 해

내 코드가 API에 의해 데이터를 반환 할 수없는 이유는 무엇입니까? 이 문제를 해결하는 방법? 내 코드가 API에 의해 데이터를 반환 할 수없는 이유는 무엇입니까? 이 문제를 해결하는 방법? Apr 01, 2025 pm 08:09 PM

내 코드가 API에 의해 데이터를 반환 할 수없는 이유는 무엇입니까? 프로그래밍에서 우리는 종종 API가 호출 될 때 NULL 값을 반환하는 문제를 겪는 경우가 종종 있습니다.

파이썬 매개 변수 주석이 문자열을 사용할 수 있습니까? 파이썬 매개 변수 주석이 문자열을 사용할 수 있습니까? Apr 01, 2025 pm 08:39 PM

파이썬 프로그래밍에서 Python 매개 변수 주석의 대체 사용법, 매개 변수 주석은 개발자가 기능을 더 잘 이해하고 사용하는 데 도움이되는 매우 유용한 기능입니다 ...

Python 스크립트는 특정 위치에서 Cursor 위치로 출력을 어떻게 제거합니까? Python 스크립트는 특정 위치에서 Cursor 위치로 출력을 어떻게 제거합니까? Apr 01, 2025 pm 11:30 PM

Python 스크립트는 특정 위치에서 Cursor 위치로 출력을 어떻게 제거합니까? Python 스크립트를 작성할 때 이전 출력을 커서 위치로 지우는 것이 일반적입니다 ...

Python Cross-Platform 데스크탑 응용 프로그램 개발 : 어떤 GUI 라이브러리가 가장 적합합니까? Python Cross-Platform 데스크탑 응용 프로그램 개발 : 어떤 GUI 라이브러리가 가장 적합합니까? Apr 01, 2025 pm 05:24 PM

Python 크로스 플랫폼 데스크톱 응용 프로그램 개발 라이브러리 선택 많은 Python 개발자가 Windows 및 Linux 시스템 모두에서 실행할 수있는 데스크탑 응용 프로그램을 개발하고자합니다 ...

파이썬 모래시 그래프 그리기 : 가변적 인 정의되지 않은 오류를 피하는 방법? 파이썬 모래시 그래프 그리기 : 가변적 인 정의되지 않은 오류를 피하는 방법? Apr 01, 2025 pm 06:27 PM

Python : 모래 시계 그래픽 도면 및 입력 검증을 시작 하기이 기사는 모래 시계 그래픽 드로잉 프로그램에서 Python 초보자가 발생하는 변수 정의 문제를 해결합니다. 암호...

파이썬에서 대형 제품 데이터 세트를 효율적으로 계산하고 정렬하는 방법은 무엇입니까? 파이썬에서 대형 제품 데이터 세트를 효율적으로 계산하고 정렬하는 방법은 무엇입니까? Apr 01, 2025 pm 08:03 PM

데이터 변환 및 통계 : 대규모 데이터 세트의 효율적인 처리이 기사는 제품 정보가 포함 된 데이터 목록을 다른 사람으로 변환하는 방법을 자세히 소개합니다 ...

See all articles