python的字符串类型本质上是一种字符序列_20170402Python变量类型 知识点梳理

Python变量类型 知识点梳理

Python变量类型包括:

None

str

unicode

float

bool

int

long

用于表示数字的主要的python类型是int和float。

Python字符串

字符串,本质上是一串字符序列。

字符串变量表示方法。即可使用单引号,也可以使用双引号:

a = “My name is”

b = ‘I am’

对于带有换行符的多行字符串,可以使用三重引号(即’’’或者”””):

c = “””

This is a longer string that

spans multiple lines

“””

或者:

c = ‘’’

This is a longer string that

spans multiple lines

‘’’

Python字符串是不可变的。要修改只能创建一个新的字符串

>>> a = ‘this is a string’

>>> b = a.replace(“string” , “ longer string ”)

>>> b

>>> ‘this is a longer string’

字符串格式化。这是需要研究的重点,通用字符串的处理,对数据分析非常重要。更多关于字符串的操作细节可参考利用Python进行数据分析第7章数据规整化P217页字符串操作。

>>> template = " %.2f %s are worth $%d "

>>> template % (4.5560 , 'Argentine Pesos' , 1)

' 4.56 Argentine Pesos are worth $1 '

>>>

布尔值。Python中大部分对象都有雨真假的概念。比如说,如果空序列(列表、字典、元组等)用于控制流就会被当做False处理。想知道某个对象究竟会被强制转化成哪个布尔值,使用bool函数即可。

>>> bool([]),bool([1,2,3])

(False, True)

>>> bool([ ])

False

>>> bool(0),bool(1)

(False, True)

>>> bool ( "Hello , world" ),bool(" ")

(True, True)

>>> bool('')

False

>>>

类型转换。str、bool、int、float等类型也可用作将值转换成该类型的函数。

None,None是Python的空置类型。如果一个函数没有显示地返回值,则隐式返回None。

None还是函数可选参数的一种常见默认值,定义函数时某个参数默认为None。

日期和时间。Python内置的datetime模块提供了datetime、date以及time等类型

>>> from datetime import datetime , date , time

>>> dt = datetime(2017,4,2,19,2,24)

>>> dt.day

2

>>> dt.hour

19

>>> dt.minute

2

>>> dt.date()

datetime.date(2017, 4, 2)

>>> dt.time()

datetime.time(19, 2, 24)

>>>

strftime方法用于将datetime格式化为字符串:

>>> dt.strftime('%m/%d/%y %H:%M')

'04/02/17 19:02'

>>>

字符串可以通过strptime函数转化(解析)为datetime对象:

>>> datetime.strptime ("201741","%Y%m%d")

datetime.datetime(2017, 4, 1, 0, 0)

>>>

在对时间序列数据进行聚合或分组时,可能需要替换datetime中的一些字段。例如,将分和秒字段替换为0,并产生一个新的对象。

>>> dt.replace (minute = 0,second = 0 )

datetime.datetime(2017, 4, 2, 19, 0)

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值