Chapter 4: String

PART 1: A First Look at the string

  1. The format string format

   % Left right

   Left: placing a string

   Right: put a value desired to be formatted

= fomat " Hello,% S,% S enough for Ya !! " 
values = ( " World! " , " Hot " )
 # a string format, if the values for a plurality of values should be placed in neuron progenitor 
print (fomat% values) 

result:
! the Hello, world, Hot enough for Ya !!

   2. Basic conversion specifier

  • Mark the beginning of conversion of the specification: the% character
  • Conversion flag (optional): - represents a left-aligned; + means to add the converted value before the sign; "" represents a reserved space before positive number; 0 if converted value represents the number of bits is not enough to fill 0
  • Minimum field width (optional): the converted string should have at least the value of a specified width
  • Followed by point accuracy (optional) (.): If the conversion of a real number precision value is now shown digits after the decimal point, if the conversion is a string, then the field number means the maximum width, if it is *, then precision read from tuple.

   Simple format

# 简单转化
print("%s plus %s equal %s" % (1,2,3))
print("Price of eggs: $%d" % 42)
print("Price of eggs: $%x" % 42)

import math
print(math.pi)
print("pi:%f ..." % math.pi)

结果:
1 plus 2 equal 3
Price of eggs: $42
Price of eggs: $2a
3.141592653589793
pi:3.141593 ...

  Field width and precision

# Field width and precision 
from Math Import PI
 # 1OF denotes the width of the float 10 
Print ( " % 1OF " % PI)
 # 2 represents 10 denotes the width accuracy, after the 
Print ( " % 10.2f " % PI)
 Print ( " % .2f " % PI)
 # point precision value followed by (optional) (.): If the real-transformed 
# precision value is now shown after the decimal point 
# if the conversion is a string, then the number is represents the maximum field width 
# If the "*", then the accuracy will read from tuple 
Print ( " % 10.5 second " % " Python iS Great!")
print("%.5s" % "python is great!")
print("%*.*s" % (10,6,"python is great!"))
print("%.*s" % (3,"python is great!"))

result:
  3.141593
      3.14
3.14
     pytho
pytho
    python
question

   Symbol, alignment, filled with 0

# Symbol, aligned and padded with zeros 
from Math Import PI
 # "010" of a mean octal 0 
# represents a width of 10, and the gap is filled with 0 
Print ( " ============ filling vacated 0 ============= " )
 Print ( " % 1OF " % PI)
 Print ( " % 010f " % PI)
 Print ( " % 10.2f " % PI)
 Print ( " % 010.2f " % PI)
 Print ( " ============ '-'For left-aligned =============" )
 Print ( " % 10.2f " % PI)
 Print ( " % -10.2f " % PI)
 Print ( " ============ "" represents a positive number before adding a space === ========== " )
 Print ( " ============ " + " represents a plus sign before conversion =========== == " )
 Print (( " % 5D " % 10) + " \ n- " + ( " % 5D " % -10))
print(("%+5d" % 10) + "\n" + ("%+5d" % -10))

result:
============ filling vacancies ============= 0
  3.141593
003.141593
      3.14
0000003.14
============ ' - ' represents a left alignment =============
      3.14
3.14      
============ ============= represented by a space before positive numbers
============ plus sign indicates ============= before conversion
   10
  -10
  +10
  -10

 Lecture 2: string methods

  1. find method

   can find find substring in a string, the substring in the parent returns the string occupies the leftmost position index

   find(sub,start,end)

# The Find method returns a string leftmost Index 
# -1 if not found returns 
title = " Monty Python's Flying Circus! " 
Print (title.find ( " Python " ))
 Print (title.find ( " Python " , 7 ))
 Print (title.find ( " Python " , 6,20)) 

results:
. 6
-1
. 6

   2.join Method: string concatenated

   Note: The elements are connected string

# The Join Method 
# sequence elements must be connected to the string 
student_names = [ " Alice " , " Bob " , " Bela " ]
 Print ( " + " .join (student_names))
 # Numbers = [l, 2,3] 
# Print (. "+" join (numbers )) # saves the statement, reasons: sequence elements must be connected to a string 
dirs = ( "" , " Home " , " Bob " )
dirs1 = ["","home","bob"]
print("/".join(dirs))
print("/".join(dirs1))
print("c:"+"\\".join(dirs))

result:
Alice + Bob + Beautiful
 / home / bob
 / home / bob
c:\home\bob

 

   3.spit method: cutting string as an element in the list

   Default SPIT () without parameters, segmentation is performed in accordance with the space

 

sentence = "Hello world!"
print(sentence.split())
numbers = "1+2+3+4"
print(numbers.split())
print(numbers.split("+"))

result:
['Hello', 'world!']
['1+2+3+4']
['1', '2', '3', '4']

 

   4.lower () to convert strings to lower

names = "Hello World!"
print(names.lower())
student_names = ["alice","bob","bela"]
student_name = "Bela"

if student_name.lower()in student_names:
    print(True)
else:
    print(False)

result:
hello world!
True

   5.replace: The specified string is replaced with the target string

   replace (oldsub.newsub.n) n refers to the number of the replacement string

   strip () remove the specified string or strings on both sides of a space

# replace 方法
print("This is an apple.".replace("apple","orange"))
print("This is an apple apples.".replace("apple","orange"))
# replace 第3个参数,指定替换次数
print("This is an apple apples.".replace("apple","orange",1))

 

# strip方法
name = " Bela "
names = ["alice","leo","bela"]
namebak = name.lower()
if namebak.strip() in names:
    print(True)
else:
    print(False)

str = "*** python * for program language!***"
print(str.strip("*"))
print("*** python * for program language!***".strip("!"))
print("*** python * for program language!***".strip("*"))


结果:
True
 python * for program language!
*** python * for program language!***
 python * for program language!

   6. translate simultaneously replacing the plurality of characters

    Note: generally used in combination with the function maketrans

   maketrans Method: receiving two parameters, and the like are two length parameters, the first parameter is the string to be converted, and the second parameter is a target to be converted

   translate method: only one parameter must be a dict type

  List: [], ancestral :(), the dictionary: {}

str = "this is a string demo……wow!!"
intab = "aeiou"
outtab ="12345"
trantab = str.maketrans(intab,outtab)
print(trantab)
print(str.translate(trantab))

result:
{97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
th3s 3s 1 str3ng d2m4……w4w!!

 Lecture 3: string formatting Case

 Case: to use the name and price of fruit after a given width, print format

# String format Case 
# given the width of the print format name and price of fruit 
width = int (the INPUT ( " Please the INPUT width: " ))
price_width =. 8 
item_width = width - price_width
 Print ( " = " * width)
 # header_format represented header, a string 
# represents the content conFormat, * 2f price of real numbers, accurate to one decimal two. 
header_format = " % - * S % - * S " 
conFormat = " % - S% * -. *. 2F " 
Print (header_format% (item_width, " the Name " , price_width, " Price " ))
 Print ( " - " * width)
 Print(conFormat % (item_width,"Apple",price_width,5.89))
print(conFormat % (item_width,"Orange",price_width,4.123))
print(conFormat % (item_width,"Banana",price_width,3.1))


result:

please input width:20
====================
Name        Price   
--------------------
Apple       5.89    
Orange      4.12    
Banana      3.10    

 

Guess you like

Origin www.cnblogs.com/ling07/p/10681046.html