Python string, dictionary operation, file read/write

Source: Internet
Author: User

One, string manipulation:
name = ' Aabc,dddd,a '
name1 = ' Q '
# print (name[3]) #字符串也可以取下标
# Print (Name.capitalize ()) #把字符串首字母大写
# Print (Name.center (one, ' * ')) #把name放中间, string less than 11, then complete with *
# #print (Name.index (' P ')) #返回字符串的索引, error not found, substring not found
# Print (Name.isalnum ()) #只能有数字或字母, returns ture, contains other symbols or punctuation, and spaces false
# Print (Name.isalpha ()) #字符串必须为英文或汉字, returns True
Print (Name.istitle ()) #判断是不是标题 (capital letter)
# print (name)

#**********************************
# Print (Name.count (' s)) #查询出现的次数, no then return 0

# Print (Name.endswith (' Zuo ')) #判断是否zu结束, returns a Boolean value
# Print (Name.startswith (' h ')) #判断是否开头, returns a Boolean value

# Print (Name.upper ()) #都变成大写
# Print (Name.lower ()) #都变成小写
# Print (Name.find (' 1 ')) #返回字符串的索引, return-1 when not found, recommended use
# Print (Name.isdigit ()) #判断是否为纯数字, returns a Boolean value
# Print (Name.isidentifier ()) #判断它是不是一个合法的变量名,
# Print (Name1.isspace ()) #判断是否全是空格

# Print (Name.strip ()) #去掉字符串两边的东西, without parameters the default is to remove both spaces and newline characters \ n
# Print (Name.lstrip ()) #只去掉左边的
# Print (Name.rstrip ()) #只去掉右边的

Print (Name.replace (' abc ', ' X ')) #替换字符串, replace the front with the back, the default is replace All, Name.replace (' abc ', ' X ', 2) 2 means to replace several places
Print (Name.zfill) #在前面补0, fill 19 characters

Print (Name.split (', ')) #1. Split string, the default is space and newline, ', ' as the delimiter 2. Turn the string into a list
#name. Split (', ', 1) 1 means split 1 times, followed by an element

Stus = [' aabc ', ' dddd ', ' a ']
Print (' * '. Join (Stus)) #1. Change list to string 2. Concatenate with * string
#********************************

Import string
Print (string.ascii_letters) #所有的大写 + lowercase Letters
Print (string.ascii_lowercase) #所有小写字母
Print (string.ascii_uppercase) #所有大写字母
Print (string.digits) #所有数字
Print (string.punctuation) #所以特殊字符


Second, the dictionary
#非空即真, not 0 is true
#实现同样的功能, the less code, the better.
#假 empty list, empty string, empty tuple, 0, None
# not take reverse
# a = []
# b = "
# c = ()
# d = 0
# e = None
# if E:
# print (1)
# Else:
# print (0)
# import this

#字典 K-v Dictionary unordered
Shenyang = {' name ': ' Shenyang ',
' Age ': 18,
' Sex ': ' Don't Know ',
' Addr ': ' Tian Tong Yuan ',
' QQ ': 123456,
' Email ': ' [email protected] '
}
Print (Shenyang)

#增加
shenyang[' girlfriend '] = ' very beautiful '

shenyang[' age ' = #k不管是否存在, non-existent then incremented, existing modified
Print (Shenyang)
Shenyang.setdefault (' Age ', "#不存在") is incremented, and if K already exists, it will not be modified,
Print (Shenyang)

#修改
shenyang[' girlfriend '] = ' very beautiful '

#删除
# Shenyang.pop (' female friends ') #删除时key不存在, will error
# del shenyang[' AG ' #删除时key不存在, will error

#查, take a value
Print (shenyang[' addr ')) #key not present, error
Print (shenyang.get (' email ')) #key not present, return none
Print (Shenyang)
Print (Shenyang.get (' EMAILWW '))
#shenyang. Clear () #清空字典
#shenyang. Popitem () #随机删除一个key
Yaoyuan = {' Chouyan ': ' 1 '}
Shenyang.update (Yaoyuan) #把字典yaoyuan加入到另一个字典shenyang, duplicate, update value
Print (Shenyang.values ())
Print (Shenyang.keys ())

For I in Shenyang: #默认循环的是key
Print (i)

For I in Shenyang.items (): #默认循环的是key
Print (i)
For i,j in Shenyang.items (): #循环的是key和valus
Print (I,J)

D = {' A ': 1, ' B ': 2}
Print (D.items ())

For k,v in D.items (): #会字典转换成list, low efficiency
Print (K,V)

For k in D: #打印key和value的值, recommended this way, fast
Print (K,d.get (k))

info = [
{
' Xiaohei ':
{
' Money ': 10000,
' Cars ': [' ben-z ', ' Audi ', ' BMW '],
' Info ': {
' Phone ': 186212312,
' Age ': 36,}
}
},
{' Xiaohong ':
{
' House ': {
' Chaoyang ': 2,
' Haidian ': 3,
' Changping ': 5
},
' LAN ': [' ch ', ' en ', ' JP '],
}
}
]
Print (info)
info[0][' Xiaohei ' [' Cars '].append (' BSJ ') #car里加bsj
Print (info)
info[0][' Xiaohei ' [' Info '] [' addr '] = ' AA '
info[1][' Xiaohong ' [' House '] [' haidian '] + = 2
Print (info[1][' xiaohong ' [' House '] [' Haidian '])
Print (info)
info[1][' Xiaohong ' [' sex '] = ' female '
Print (info)

Iii. file reading and writing
#1, open File
#2, to read/write
#3, close files
#f = open (' ABC Chinese-TXT ', encoding= ' utf-8 ')
There's no way to use the File,python3 in #python2.
f = open (' ABC Chinese. txt ', ' A + ')
#文件指针 ************
# print (' ReadLine ', F.readline ()) #读取文件的一行数据
# print (' ReadLines ', F.readlines ()) #读取所有文件内容, return a list, the element is the data of each row, do not use the large file, because the contents of the file will be read into memory, memory is not enough, the memory will be blown
# print (' read ', F.read ()) #获取文件里面的所有内容

F.write (' abc ')
F.close ()
f = open (' ABC Chinese. txt ', ' A + ')
Print (F.read ())

#文件的三种模式 read-only, write mode, append mode
#r default read-only mode, read only, not writable, file does not exist will error
#r + read-write mode, readable, can be appended, file does not exist will error

#w write mode, unreadable, overwrites the previous file contents, and the file does not exist the new
#w + write mode, readable, overwrites the previous file contents, the file does not exist the new

#a Append mode is unreadable, does not exist, is created, and only appends content, the file opens the pointer at the end, so the content is not read
#a + Append read mode can be read, not exist then create, only append content to exist

#只要和r相关的, the file does not exist, the error
# as long as W related, the contents of the file will be emptied


F.seek (0)
Print (' read ', F.read ())

names = [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']

For name in Names:
F.write (name + ' \ n ')
F.writelines (names)

V. List slices

#切片, the list is a way of taking a value, slicing, the same applies to string *******************************
Stus = [' Lxy ', ' zyf ', ' Wdz ', ' N1 ', ' wy ', ' GFW ']
Import string
# print (Stus[1:3]) #顾头不顾尾
# print (Stus[:3]) #从最前开始取值
# print (Stus[-1]) #-1 represents the last element
# print (stus[1:]) #取值到最后
# print (stus[:]) #取整个list
# print (stus) #取整个list

Print (String.digits.split ())
Nums = List (string.digits) #强制类型转换
Print (Nums)
Print (Nums[0:11:2]) #步长, default is 1
Print (Nums[9:0:-1]) #从后往前取值, default is 1

A = ' abcdef '
Print (A[1:3])

Six, the tuple
# Immutable index with Count method after definition
City = (' AA ', 1,2,2,2,2)
Print (city)
Print (City[0])
Print (City.index (2))
Print (City.count (2))

# s = ' a,b,c,d '
# print (s)
# new_s = S.replace (' A ', ' 111 ')
# print (s)
# Print (new_s)

Python string, dictionary operation, file read/write

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.