Home  >  Article  >  Backend Development  >  What are the basic data types in python?

What are the basic data types in python?

青灯夜游
青灯夜游forward
2018-10-19 16:18:544862browse

The content of this article is to introduce the basic data types of python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Everything in python is an object, and an object is a whole containing attributes and methods.

2. The composition of the data type: identity (memory address, its unique identifier can be seen through the id method); type (viewed through the type method); value (data item)

3 , Commonly used basic data types

  • int Integer

  • bool Boolean

  • strintg String

  • list List

  • tuple Tuple

  • dict Dictionary

4. Variable and immutable data types

  • Immutable types: int, string, tuple

  • Variable types : list, dict

5, escape character

#转义字符
print('abcd\nef')#\为转义字符
print(r'abcd\nef')#字符串前面加r表示不转义

运行结果:
abcd
ef
abcd\nef

6, slice

a = "abcde"
b = a[-1] #访问最后一个元素
c = a[0:4]#访问序列在0到4之间的元素不包括4
print(b)
print(c)

运行结果:
e
abcd

7, string replacement

a = "abcd"
print(a[0])
b = a.replace('d','def')
print(b)
print(a.find('d'))#字符串查询

运行结果:
a
abcdef
3

8. String splicing

#【1】直接相加
a = 'my name is xiaobin'
b = 'tong'
c = a + b
print(c)

运行结果:
my name is xiaobintong

#【2】占位符
print('my name is %s xiaobin' % 'tong')#%s为字符串占位符,%d为数字占位符
print('my name is %s xiaobin,i\'m %s years old' % ('tong',24))

print('my name is {1}, i\'m {0} years old'.format('24','tongxiaobin'))#用format方法

运行结果:
my name is tong xiaobin
my name is tong xiaobin,i'm 24 years old
my name is tongxiaobin, i'm 24 years old

#【3】join
a = '123'
b = '456'
c = '789'
d = ''.join([a,b,c])
e = ';'.join([a,b,c])
print(d)
print(e)
运行结果:
123456789
123;456;789

9. File operations: 'r'-read; 'w'-write; 'a'-append (add at the end)

#写操作
d = open('1.txt','w')
d.write('hello world\nmy name is tongxiaobin')
d.close()

#读操作
e = open('1.txt','r')
print(e.readline())#按行读取
print(e.readline())

运行结果:
hello world
my name is tongxiaobin

#末尾添加操作
a = open('1.txt','a')
a.write('\ncome from anhui')
a.close()

打开文件结果为:
hello world
my name is tongxiaobinfdsd
come from anhui

10. linecache module

import linecache
linecache.getline('1.txt',2)

运行结果:
'my name is tongxiaobin\n'

linecache.getlines('1.txt')

运行结果:
['hello world\n', 'my name is tongxiaobin\n', 'come from anhui\n']

Summary: The above is the entire content of this article, I hope it will be helpful to everyone’s study. For more related video tutorials, please visit: Python video tutorial, Python3 video tutorial, bootstrap video tutorial!

The above is the detailed content of What are the basic data types in python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete