Maison développement back-end Tutoriel Python python编程开发之textwrap文本样式处理技巧

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

Jun 10, 2016 pm 03:07 PM
python Développement de programmation

本文实例讲述了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()

Copier après la connexion

输出效果:

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

Copier après la connexion

我们会发现,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()

Copier après la connexion

运行效果:

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

Copier après la connexion

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

Copier après la connexion

运行效果:

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

Copier après la connexion

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

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
2 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Repo: Comment relancer ses coéquipiers
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Comment copier efficacement la colonne entière d'une dataframe dans une autre dataframe avec différentes structures dans Python? Comment copier efficacement la colonne entière d'une dataframe dans une autre dataframe avec différentes structures dans Python? Apr 01, 2025 pm 11:15 PM

Lorsque vous utilisez la bibliothèque Pandas de Python, comment copier des colonnes entières entre deux frames de données avec différentes structures est un problème courant. Supposons que nous ayons deux dats ...

Les annotations des paramètres Python peuvent-elles utiliser des chaînes? Les annotations des paramètres Python peuvent-elles utiliser des chaînes? Apr 01, 2025 pm 08:39 PM

Utilisation alternative des annotations des paramètres Python Dans la programmation Python, les annotations des paramètres sont une fonction très utile qui peut aider les développeurs à mieux comprendre et utiliser les fonctions ...

Comment les scripts Python effacent-ils la sortie en position de curseur à un emplacement spécifique? Comment les scripts Python effacent-ils la sortie en position de curseur à un emplacement spécifique? Apr 01, 2025 pm 11:30 PM

Comment les scripts Python effacent-ils la sortie en position de curseur à un emplacement spécifique? Lors de l'écriture de scripts Python, il est courant d'effacer la sortie précédente à la position du curseur ...

Pourquoi mon code ne peut-il pas faire renvoyer les données par l'API? Comment résoudre ce problème? Pourquoi mon code ne peut-il pas faire renvoyer les données par l'API? Comment résoudre ce problème? Apr 01, 2025 pm 08:09 PM

Pourquoi mon code ne peut-il pas faire renvoyer les données par l'API? En programmation, nous rencontrons souvent le problème du retour des valeurs nulles lorsque l'API appelle, ce qui n'est pas seulement déroutant ...

Comment Uvicorn écoute-t-il en permanence les demandes HTTP sans servir_forever ()? Comment Uvicorn écoute-t-il en permanence les demandes HTTP sans servir_forever ()? Apr 01, 2025 pm 10:51 PM

Comment Uvicorn écoute-t-il en permanence les demandes HTTP? Uvicorn est un serveur Web léger basé sur ASGI. L'une de ses fonctions principales est d'écouter les demandes HTTP et de procéder ...

Comment créer dynamiquement un objet via une chaîne et appeler ses méthodes dans Python? Comment créer dynamiquement un objet via une chaîne et appeler ses méthodes dans Python? Apr 01, 2025 pm 11:18 PM

Dans Python, comment créer dynamiquement un objet via une chaîne et appeler ses méthodes? Il s'agit d'une exigence de programmation courante, surtout si elle doit être configurée ou exécutée ...

Comment utiliser GO ou Rust pour appeler les scripts Python pour réaliser une véritable exécution parallèle? Comment utiliser GO ou Rust pour appeler les scripts Python pour réaliser une véritable exécution parallèle? Apr 01, 2025 pm 11:39 PM

Comment utiliser GO ou Rust pour appeler les scripts Python pour réaliser une véritable exécution parallèle? Récemment, j'ai utilisé Python ...

Où télécharger des fichiers python .whl sous Windows? Où télécharger des fichiers python .whl sous Windows? Apr 01, 2025 pm 08:18 PM

Python Binary Library (.WHL) Méthode de téléchargement explore les difficultés que de nombreux développeurs Python rencontrent lors de l'installation de certaines bibliothèques sur les systèmes Windows. Une solution courante ...

See all articles