Python-Ref > String manipulation > String basics > Analyzing a string
 
 

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

Analyzing a string

Finding out about parts of a string
The string object specifies many very useful methods. Several of them may be used to analyze parts of the string.
Expand/Shrink
  1   text_long = "There were 42 monkeys in the airplane."
  2   text_word = "hello"
  3   text_title = "String Methods"
  4   
  5   for t in [text_long, text_word, text_title]:
  6       print '"%s"' % t
  7       print "Count 'th':      ",t.count( 'th')
  8       print "Count 'l':       ",t.count( 'l')
  9       print "Startswith 'St': ",t.startswith("St")
 10       print "Endswith '.':    ",t.endswith(".")
 11       print "Find 'l':        ",t.find('l')
 12       print "Rfind 'l':       ",t.rfind('l')
 13       print
stdout:
"There were 42 monkeys in the airplane."
Count 'th':       1
Count 'l':        1
Startswith 'St':  False
Endswith '.':     True
Find 'l':         33
Rfind 'l':        33

"hello"
Count 'th':       0
Count 'l':        2
Startswith 'St':  False
Endswith '.':     False
Find 'l':         2
Rfind 'l':        3

"String Methods"
Count 'th':       1
Count 'l':        0
Startswith 'St':  True
Endswith '.':     False
Find 'l':         -1
Rfind 'l':        -1

Doba běhu: 13.7 ms