Three: python data types and file operations

Source: Internet
Author: User
Tags save file string methods uppercase letter

One: string manipulation

1. The string can be evaluated by subscript, but because the string is immutable, it cannot be modified by Subscript.

Username = ' Li ' username[0]2.The For loop in python, each time the loop is looped, each element inside the Loop object3.Len (names) #取变量的长度4.#!/usr/bin/python #python里面有个这个话, on behalf of Linux under the runtime, to which directory to find the Python interpreter, run on Windows do not write5.# coding:utf-8 # __*__ Coding:utf-8 __*__ above both of these are in the python2 in order to prevent Chinese error, modify the character set used, Python3 inside do not write6.All string methods, It will not modify the value of the original string, will produce a new string7.coercion type conversion function

#int ()
#float ()
#str ()
#list ()
#tuple ()

8. String methods that must be known and will beImport String#print (string.ascii_letters+string.digits) #大小写字母 + number #print (name.find (' SSS ')) # Find the index of the string, Find the words return the first occurrence of the index, cannot find the return -1#print (name.format (name= ' niuniu ', age=18)) #格式化字符串 #print (' abA123 '. isalnum ()) # Whether it contains numbers and letters #print (' 122 '. isdigit ()) # is the number #print (name.lower ()) # becomes lowercase #print (name.upper ()) # becomes uppercase #strnames = ' ABCEDF ' #print (' ¥ '. Join (STRNAMES)) # join is the # print (' \nmysql \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ ") that uses a string to stitch each element of an iterative Object. strip () Mysqlm '. strip (' m ')) #当你传入某个字符串的话, It will only remove the string you specified #print (st.replace (' mysql ', ' Oracle ')) # Replace string #name1 = ' zcl p y zyz ' print ( Name1.split ()) #切割字符串, Returns a list, separates the string according to the string you specify, and then puts it in a list, and if you don't write anything, divide by space, and multiple spaces are counted as one9. String Methods

name = ' HeLLo World '
Import string
Print (string.ascii_letters+string.digits) #大小写字母 + digits
Print (string.ascii_lowercase) #所有的小写字母
Print (string.ascii_uppercase) #所有的大写字母
Print (string.digits) #所有的数字
# print (name.capitalize ()) # capitalize first letter
# print (name.center (5, ' * ')) # 50--put The name in the middle
# print (name.endswith (' d ')) # Does it end with X
# print (name.find (' sss '))
# Find the index of the string, find the words to return the first occurrence of the index, can not find the return-1
# print (name.format (name= ' Niuniu ', age=18)) # This is the format string, and then the first section of the blog has been written
# print (name.format_map ({' name ': ' Niuniu ', ' age ': 19}) # This is also a formatted string, followed by a dictionary, the dictionary will be written in the back
# print (' abA123 '. isalnum ()) # Whether it contains numbers and letters
# print (' AbA '. isalpha ()) # is the English alphabet

# print (' 122 '. isdigit ()) # is the number
# print (' 11sdf '. isidentifier ()) # is a valid variable name
# print (' AA '. islower ()) # Whether it is a lowercase letter
# print (' AA '. isupper ()) # Whether it is an uppercase letter
# print (name.lower ()) # turns lowercase
# print (name.upper ()) # becomes uppercase
names = [' zcl ', ' py ', ' Zyz ']

Strnames = ' ABCEDF '
# print (' ¥ '. join (STRNAMES))
# print (' strname: ', strnames)
# join is used to stitch each element of an iterative object through a string.

#所有字符串的方法, It will not modify the value of the original string, it will produce a new string
# Print (' wubing\nhouning ')


# print (' \nmysql \ n '. lstrip ()) # by default, the left space and line breaks are removed
# print (' \nmysql \ n '. rstrip ()) # Default to remove the right space and line breaks
# print (' \nmysql \ n '. strip ()) # Default to remove whitespace and line breaks on both sides
# print (' mysqlm '. strip (' m ')) #当你传入某个字符串的话, It will only remove the string you specified


# p = Str.maketrans (' abcdefg ', ' 1234567 ') # precedes the string and follows the string to do the mapping
# print (' Ccaegg '. translate (p)) # outputs a mapped string following the Maketrans above
#
# new_p = Str.maketrans (' 1234567 ', ' ABCDEFG ')
# print (' Ccaegg '. translate (new_p))
St= ' MySQL is Db. MySQL Mysql-mysql '
Print (st.replace (' mysql ', ' Oracle ')) # Replace string

# print (' MySQL is a db '. rfind (' is ') # returns the subscript of the rightmost character

# names = [' zcl ', ' py ', ' Zyz ')
New_name = []
#1, have a list to save it first
Comma-separated values #2 and loops
name1 = ' zcl p y zyz '

# Print (name1.split ())
#切割字符串, return a list, separate the string according to the string you specified, and put it in a list
#如果你什么都不写的话, separated by a space, multiple spaces are counted as a

# print (' 1+2+3+4 '. split ()) # cut string, return a list
# print (' 1+2+3\n1+2+3+4 '. splitlines ()) # Split by line break
# print (' Abcdef '. swapcase ()) # case reversal

A = 0
b = 2
#不引入第三个变量
A = A+b
#a是3

b = A A
#b是1
A = A-b
#a是2
Print (' ===== Here's what we're looking for ')
Print (a, B)

#引入第三个变量的方法
# c = A
# #c是1
# a = b
# #a是2
# b = C
# Print (a, B)

#不用第三方变量, Exchange the values of A and B.
# a, B = b,a
# print (' A: ', a)
# print (' B: ', b)
a, B = b,a
Print (' A: ', a)
Print (' B: ', b)

second, List Operation1. The list is a mutable variable, which can be used to change the value of the Subscript.  names = [liliyun, ' Panyang '] #定义列表   # print (names[3]) #通过下标取值   names[0]= ' Zhangyizhou ' #修改值   Names.append (' zhaocunlei ') #给list从最末尾添加值   names.insert (0, ' Yinwenqiao ') #指定位置添加元素   # print (' before '), Names)   # Print (' pop return value: ', names.pop ())   # Print (' Remove method return value ', names.remove (' yinwenqiao '))   # del names[0] #使用del关键字删除指定元素   # names.pop () #默认删除最后一个元素, Delete who also returns its value   # Names.pop (2) #删除指定位置的元素   # names.clear () #清空列表   # names.remove (' Yinwenqiao ') # Delete the specified value, to distinguish it from the pop method, if the pop is deleted, the pass is subscript,  # Reomve is the value of an element   # print ( Names.count (' hsdfsdf ')) #查找值在list里面的次数   # print (' names ', names)   # print (names.index (' yinwenqiao ')) # Returns the index of the lookup element, if there are multiple words to return the first, if not, then error   # print (names.index (' yinwenqiao ', 3,4)) #后面可以加上查找开始位置和结束位置   Stus = [' YANGWB ', ' yangwn ', ' yanghj ']  # print (' add up ', stus+names) #两个列表合并   # print (' This is extend: ', stus.extend (NAMES)) # Add each value from the other list to the previous list   # print (' This is extend: ', stus)   # nums = [23,34,21,2,456,35,12324324]  # Nums.sort () #排序, default is ascending   # print (' sort: ', nums)   # print (nums.sort (reverse=true)) #排序, Specify reverse= True is descending   # print (' sort descending: ', nums)   # print (nums.reverse ())   # print (nums)   # print (' Zhangyizhou ' in Names) #用in来判断一个元素是否在list里面   # print (names[-3]) #下标是-1, which represents the last element    #循环列表    # for name in names :  # print (name)    #多维数组, list, list  lis = [1, ' lily ', 19.8,[' lily ', ' Lilei ', [' heheh ', ' haha ']]]  Print (lis[3][2][1])   a1 =[1,2,3]  a2 = [4,5,6]  # a1.extend (a2)   a1.append (a2)   Print (a1)   three, Slice slicing means taking a few elements from a list or a string.
Slice operations are also fully applicable to Strings.

name1 = ' Zcl,pyzyz '
names = [' zcl ', ' py ', ' Zyz ']
# Print (names[0:2]) # take from the first few to the first, this is also Gu Tou disregard the tail
# Print (names[:2]) # If you take it from the first one and take it to the end of a subscript, you can never write it in front of YOU.
# print (names[1:]) #如果是从前面某个开始取, take to the end of the last face, then you can not write at the back
# print (names[:]) #如果最前面和最后面都不写的话, take the entire list

#nums = List (range (1,11))
# print (nums[1:10:2]) #如果最后面写上步长的话, just take it every few
# Nums.reverse ()
Print (nums)
Print (nums[::2])
Print (nums[::-2])
Print (nums[::-1])
#当切片的步长为负数时, The value is taken from the end, and then taken once every
#如果步长为-1, There's a reversal Function.

four, the tuple

Lis = [' 127.0.0.1 ', ' 3306 ']
TP = (1,2,3,4,5,6,1,1,1)
lis[1]= ' 3307 '
Print (lis)
Print (tp[0])
Print (tp.count (1))
Print (tp.index (1))
#元组是一个不可变的list, only the Count method and the index method
#定义元组的时候, if the tuple has only one element, then you need to add a comma after this element, or it will be a string
New_lis = Tuple (lis)
Print (type (NEW_LIS))
A= ' Hello World ' #这个是定义字符串
b= (' Hello World ',) #这个是定义元组?
Print (' This is ', type (b))

five, Dictionary1. The key in the dictionary cannot be duplicated.

info = {
' Name ': ' xiaoming ',
' Sex ': ' Nan ',
' Age ': 20,
' ID ': 1,
}

# Print (info[' ID ') #通过key取值
# print (info[' addr ') #通过key取值
# print (info.get (' ID ')) #通过key取值
# print (info.get (' addr ')) #通过key取值
2.the difference between the value of the square brackets and the get method, the Get method can not get the key, no error, the value of the brackets cannot find the key will be an error, get method may also pass a parameter, if get not key, then return to xx, if not write, Default get does not return none
info[' addr '] = ' Beijing ' #给字典新增一个值
Info.setdefault (' phone ', 13811111) #给字典新增一个值
info[' id ' = 7# in the case of this key, that is, the value of the key is modified, without this key, is the new
3. The dictionary is unordered
# del info[' addr ')
# print (info.pop (' addr '))
# Info.popitem () #随机删除一个元素
# Print (info)
#pop删除的时候必须得指定key, The Pop method returns the value corresponding to the deleted key
# info.clear ()
#清空字典

all = {
' Car ':
{
' Color ': [' red ', ' yellow ', ' black '],
' Moeny ': 1111111,
' Pailiang ': ' 2.5L ',
' Name ': "BMW"
} ,
' Car1 ':
{
' Color ': [' red ', ' yellow ', ' black '],
' Moeny ': 1111111,
' Pailiang ': ' 2.5L ',
' Country ': "china"
},
' Car2 ':
{
' Color ': [' red ', ' yellow ', ' black '],
' Moeny ': 1111111,
' Pailiang ': ' 2.5L '
}

}
# all.get (' car '). get (' color ') [1] = ' Orange '
# all[' car ' [' color '][1]= ' orange '
# Print (all)

# Print (all.keys ()) #获取该字典的所有key
# Print (all.values ()) #获取该字典所有的value
# print (all.items ()) #获取字典的key和value, loop
#直接循环字典循环的是字典的key, If you want to get the key and value in the loop
#那么就要用. Items Method
Info2 = {
' Name ': "hhh",
' Sex ': ' nan '
}
Info.update (info2) #把两个字典合并到一起, If you have the same key, update the value
# Print (info)
# Print (info2.items ())
#items方法的作用就是为了让你循环的时候同时把key和value取到
# for K,v in Info.items ():
# print ('%s is%s '% (k,v))
# for K in info2:
# Print (k)

# for K in info2:
# Print (k,info2[k])

#第二种方式效率比较高
#info. Has_key (' name ')
#python2里面有这个方法, is to determine if key is not present, python3 inside No
# Print (' name ' in Info2)
#python3里面直接用in来判断key是否存在

Vi. file reading and writing

1, Open File
2, read/write content
3, Save file
Import os
F = open (' a.txt ', ' A + ', encoding= ' Utf-8 ') #f代表的是这个文件的对象, also known as handle
F.seek (0) #移动文件指针
#文件对象也是可迭代的
# count = 0

#直接循环文件对象的话, looping through the contents of each line of the file
# res = f.read ()
# f.seek (0)
# f.truncate () #清空文件内容
# new_res = res.replace (' nihao ', ' Nibuhao ')
# f.write (new_res)
#8G的文件

# These are the
# f = open (' a.txt ', ' A + ', encoding= ' utf-8 ') that modify the contents of the file
# #f代表的是这个文件的对象, also called a handle
# F.seek (0) #移动文件指针
# fw = Open (' a.txt.new ', ' w ', encoding= ' Utf-8 ')
# for line in f:
# new_res = line.replace (' Learn ', ' don't learn ')
# fw.write (new_res)
# f.close ()
# fw.close ()
# Os. Remove (' a.txt ')
# os.rename (' a.txt.new ', ' a.txt ')


# print (f.read ()) #读文件内容, returns a string
# print (f.readlines ()) # #读文件内容, Returns a list
# Print (f.readline ()) #只读文件一行的内容
# f.write (' Zhangyizhou ') #写文件的时候, can only be a string
# f.writelines ([' 123 ', ' 456 ', ' 789 ']) #可以把列表写到里

#如果在打开的文件的时候, do not specify the mode, that is read mode
# fw = File (' a.txt ', ' r ')
#在python2里面也可以用file这个函数去操作文件, but only open in python3.

#文件打开模式有3种
#1, W Write mode, It is unreadable, if you open an existing file in W mode,
#会清空以前的文件内容, Re-write
#w +, Write-read mode, as long as the w, will definitely empty the original file
#2, R Read mode, read only, cannot write, and the file must exist
#r + is Read-write mode, as long as the r, the file must exist
#3, a append mode, also write only, add content at the end of the file
#4, rb+, wb+,ab+, This is binary mode open or read, some music files, pictures and so on

#flush用法
Import time
FW = Open (' python.txt ', ' w ', encoding= ' Utf-8 ')
Fw.write (' no class next week! ‘)
Fw.flush () #写完之后立马生效
Exit (' Goodbye ')
Time.sleep (30)
Fw.close ()


#with的用法, when your file is no longer in use, it will automatically close the file to you
# with open (' python.txt ', encoding= ' Utf-8 ') as Fr:
# Print (fr.read ())

Three: python data types and file operations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.