String
Sequence
Sequence type operator
Sequence operator
|
Role
|
Seq[ind]
|
Get the element labeled IND
|
SEQ[IND1:IND2]
|
Get subscript from Ind1 to ind2 element combination
|
SEQ * Expr
|
Sequence repeats expr times
|
SEQ1 + SEQ2
|
Connecting sequences seq1 and SEQ2
|
obj in seq
|
Determine if the obj element is included in the SEQ
|
Obj not in seq
|
Determine if the obj element is not included in the SEQ
|
Built-in functions
functions |
meaning |
list (ITER) |
Convert an iterative object to a list |
str (obj) |
Convert obj object to string |
tuple (ITER) |
Convert an iterative object to a tuple object |
/tbody>
>>> list (' Hello ')
[' H ', ' e ', ' l ', ' l ', ' O ']
>>> list ([' Hello ', ' world ')
[' Hello ', ' world ']
>>> str ([' Hello, ', ' World '])
"[' Hello, ', ' World ']"
Len (seq): Returns the length of the SEQ
Max (Iter,key=none): Returns the maximum value in ITER
>>> Max (' ABF ')
' F '
>>> Ord (' a ')
97
>>> Ord (' F ')
102
>>> Max ([10,234,3421,12])
3421
Enumerate: Takes an iterative object as a parameter and returns a enumerate object
>>> for I,j in Enumerate (alist):
... print "Index%d:%s"% (i,j)
...
Index 0:hello
Index 1:world
reversed (seq): Takes a sequence as a parameter, returning an iterator that is accessed in reverse order
sorted (ITER): Accepts an iterative object as an argument, Returns an ordered list of
> >> alist = [32,43,323,55]
> >> Sorted (alist)
[32, 43, 55, 323 ]
>>> for item in reversed ( alist):
... Print Item
           &NBSP, .....
55
323
43
32
String
String operator
Comparison operators: String sizes are compared by ASCII value size
Slice operator: [], [:], [::]
Member relationship operators: in, not in
>>> pystr = ' Hello world! '
>>> Pystr[::2]
' HLOWRD '
>>> Pystr[::-1]
'!dlrow Olleh '
Small exercise:
Check identifiers
1, the program accepts user input
3. Determine if the identifier entered by the user is legal
#!/usr/bin/env python
Import string
First_chs = String.letters + ' _ '
Other_chs = First_chs + string.digits
def check_id (myID):
If myid[0] not in First_chs:
Print "1st char invalid."
Return
For Ind,ch in Enumerate (myid[1:]):
If CH not in Other_chs:
print "Char in position:%s Invalid"% (Ind + 2)
Break
Else
Print "%s is valid"% myID
if __name__ = = ' __main__ ':
myID = Raw_input ("ID to check:")
If myID:
CHECK_ID (myID)
Else
Print "You must input an identifier."
Formatting operators
Strings can use formatting symbols to represent specific meanings
format character |
convert |
%c |
Convert to characters |
%s |
first string conversion with STR () function |
%d/%i |
turn to signed decimal number |
%o |
Turn to unsigned octal |
turn into scientific notation |
%f/%f |
turn into floating point number |
>>> "%o"% 10
' 12 '
>>> "% #o"% 10
' 012 '
>>> "% #x"% 10
' 0xa '
>>> "%e"% 1000000
' 1.000000e+06 '
>>> "%f"% 3.1415
' 3.141500 '
>>> "%4.2f"% 3.1415
' 3.14 '
format operator auxiliary instruction |
action |
* |
Define width or decimal precision (>>> "%*s%*s"% ( -8, ' name ', -5, ' age ') ' name age ' |
- |
left justified |
+ |
|
<SP> |
|
# |
Display 0 before octal number, ' 0 X ' or ' in front of hexadecimal number 0X ' |
0 |
The number displayed is preceded by 0 instead of the default Recognized spaces |
>>> "My IP is:%s"% ' 192.168.1.1 '
' My IP is:192.168.1.1 '
>>> "My IP is: {}". Format (' 192.168.1.1 ')
' My IP is:192.168.1.1 '
>>> "My IP is:{},you IP is: {}". Format (' 192.1268.1.1 ', ' 172.40.1.1 ')
' My IP is:192.1268.1.1,you IP is:172.40.1.1 '
>>> "My IP is:{1},you IP is: {0}". Format (' 192.1268.1.1 ', ' 172.40.1.1 ')
' My IP is:172.40.1.1,you IP is:192.1268.1.1 '
Little Practice
1. Prompt user input (multi-line) data
2, assuming the screen width is 50, the user entered the multi-line data display (the text content is centered):
+********************************+
+ Hello World +
+ Great work! +
+********************************+ #!/usr/bin/env python
def get_contents ():
Contents = []
while True:
data = Raw_input ("Enter to Quit") > ")
if not data:
Break
contents.append (data)
return contents
If __name__ = = ' __main__ ':
width = off
lines = get_contents ()
print ' +%s+ '% (' * ' * width)
for line in lines:
& nbsp; Sp_wid,extra = divmod (Width-len (line)), 2)
print "+%s%s%s+"% (' ' * sp_wid,line, ' * (Sp_wid + extra)
print ' +%s+ '% (' * ' * width)
String templates
String templates provide a template object that can be used to implement the functionality of a string template
>>> Import Tab
>>> Import String
>>> origtxt = "Hi ${name}, I'll see you ${day}"
>>> t = string. Template (Origtxt)
>>> t.substitute (name = ' Bob ', day = ' tomorrow ')
' Hi Bob, I'll see you tomorrow '
>>> t.substitute (name = ' Tom ', day = ' The day after Tommorrow ')
' Hi Tom, I'll see you at Tommorrow '
Little Practice
Create user
1, write a program, realize the function of creating user
2. Prompt user to enter user name
3. Randomly generate 8-bit password
4. Create a user and set a password
5, e-mail notify users of relevant information
#!/usr/bin/env python
Import Sys
Import OS
Import Randpass2
Import string
Contents = "Username: ${username}
Password: ${password}
‘‘‘
t = string. Template (contents)
def adduser (user, passwd, email):
Os.system ("Useradd%s"%user)
Os.system ("Echo%s:%s | CHPASSWD "% (Passwd,user))
#os. System ("Echo%s | passwd--stdin%s "% (Passwd,user))
data = T.substitute (Username=user,password = passwd)
Os.system ("echo-e '%s ' | Mail-s ' user info '%s '% (Data,email))
if __name__ = = ' __main__ ':
Username = sys.argv[1]
PWD = Randpass2.gen_pass ()
AddUser (Username,pwd, "[email protected]")
Primitive string Operators
Built-in functions
This article is from the Linux server blog, so be sure to keep this source http://sailq21.blog.51cto.com/6111337/1858689
Python Learning Notes Day04-python strings, lists, tuples