This article describes two important ways to use strings: string formatting and String methods.
I. String formatting
Two. String methods
The commonly used string methods are: Find,join,lower,replace,split,strip,translate.
See below for specific code
PY file
#-*-Coding:utf-8-*-
#字符串格式化
#1. Simple conversion
Print '%s plus%s equals%s '% (+/-)
From Math import Pi
print ' pi:%f ... '%pi
#2. field width and precision
print '%10f '% pi # 3.141593 field width 10
print '%10.2f '% pi # 3.14 field width 10, accuracy 2
print '%.5s '% ' abcdefgh ' #abcde
print '%.*s '% (5, ' abcdefgh ') #*
#3. symbols, 0 padding for alignment
print '%010f '%pi #003.141593 put a flag before the width precision, which can be 0, plus, minus, or space, for filling
print '%+10f '%pi # +3.141593 plus sign for glyphs
print '%-10f '%pi #减号, left-justified
Print ('%+10f '%pi) + ' \ n ' + '%+10f '%-pi # +3.141593 newline-3.141593, left justified
#字符串方法
#1. Find: Find substring, return leftmost index, no return-1
A= ' I am a student '
Print A.find (' AM ') #2
Print A.find (' Stu ') #7
Print a.find (' su ') #-1
#2. Join:split inverse method for connecting elements in a sequence
seq=[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']
A= ' + '
Print a.join (seq) #1 +2+3+4+5 Note order, not seq.join (a)
#3. Lower: Returns the lowercase master of a string
print ' Ajdoedd '. Lower ()
#4. Replace: A string that returns a string so that the match is replaced
print ' A and Hong is Friends '. Replace (' A ', ' Ming ')
#5. Split join Inverse method, divides the string into a sequence
print ' 1+2+3+4+5 '. Split (' + ') #[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']
#6. Strip returns a string that removes spaces on both sides (you can remove unintentionally added spaces)
print ' A is B '. Strip () #A is b
#7. Translate replaces some parts of a character, processing only a single character, and multiple substitutions at the same time
From string import Maketrans
Table =maketrans (' AB ', ' CD ') #maketrans函数接受两个参数: Two equal length strings with the following effect
print ' This was A and B '. Translate (table) #this is C and D
[Python Basics (ii)] string method