Python-Ref > String manipulation > String basics > Playing with whitespaces
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Playing with whitespaces

Removing whitespace, adding whitespace to perform justification, etc.
The string object specifies many very useful methods. Several of them may be used to either strip or add whitespace in different ways.
Expand/Shrink
  1   text_long = "  There were 42 monkeys in the airplane.\t"
  2   text_word = "hello  "
  3   text_title = "String Methods"
  4   
  5   for t in [text_long, text_word, text_title]:
  6       print 'Original:     "%s"' % t
  7       print 'Strip:        "%s"' % t.strip()
  8       print 'Lstrip:       "%s"' % t.lstrip()
  9       print 'Rstrip:       "%s"' % t.rstrip()
 10       print 'Center (40):  "%s"' % t.center( 40)
 11       print 'Center (40,*) "%s"' % t.center( 40, "*")
 12       print 'Rjust (40)    "%s"' % t.rjust( 40)
 13       print 'Rjust (40,-)  "%s"' % t.rjust( 40,"-")
 14       print 'Ljust (40,-)  "%s"' % t.ljust( 40,"-")
 15   
 16       print
stdout:
Original:     "  There were 42 monkeys in the airplane.	"
Strip:        "There were 42 monkeys in the airplane."
Lstrip:       "There were 42 monkeys in the airplane.	"
Rstrip:       "  There were 42 monkeys in the airplane."
Center (40):  "  There were 42 monkeys in the airplane.	"
Center (40,*) "  There were 42 monkeys in the airplane.	"
Rjust (40)    "  There were 42 monkeys in the airplane.	"
Rjust (40,-)  "  There were 42 monkeys in the airplane.	"
Ljust (40,-)  "  There were 42 monkeys in the airplane.	"

Original:     "hello  "
Strip:        "hello"
Lstrip:       "hello  "
Rstrip:       "hello"
Center (40):  "                hello                   "
Center (40,*) "****************hello  *****************"
Rjust (40)    "                                 hello  "
Rjust (40,-)  "---------------------------------hello  "
Ljust (40,-)  "hello  ---------------------------------"

Original:     "String Methods"
Strip:        "String Methods"
Lstrip:       "String Methods"
Rstrip:       "String Methods"
Center (40):  "             String Methods             "
Center (40,*) "*************String Methods*************"
Rjust (40)    "                          String Methods"
Rjust (40,-)  "--------------------------String Methods"
Ljust (40,-)  "String Methods--------------------------"

Doba běhu: 13.9 ms
Complete normalization of whitespace is described in Whitespace normalization.