Python 数据类型之字符串

格式化字符串
    参数替换(类的对象,方法调用,返回一个字符串)
    >>> username = ‘root‘
    >>> password = ‘foxconn168!‘
    >>> "{0}‘s password is {1}".format(username,password)   --> 类的对象方法调用
    "root‘s password is foxconn168!"    --> 返回一个字符串
复合字段名
    使用列表作为参数,可通过列表下标索引访问其元素
    使用字典作为参数,可通过键来访问键值
    使用模块作为参数,可通过名字访问变量和函数
    使用类作为参数,可通过名字访问方法和属性
    以上参数可任意组合
    >>> a_list = [1,2,3,4,5,6]       -->  使用列表作为参数
    >>> ‘6 * {0[0]} = {0[5]}‘.format(a_list)   --> {0[0}] 第一个参数的第一个元素
    ‘6 * 1 = 6‘
    >>>
    >>> a_dict = {Name:Sam,Age:18}     --> 使用字典作为参数
    >>> "{0[Name]}‘s age is {0[Age]}".format(a_dict)  --> {0[0}] 第一个参数的第一个元素
    "Sam‘s age is 18"

格式说明符
    ‘{0:.1f} {1}‘.format(size, suffix)
        --> {0:0.1f} 0 为第一个参数;:为格式说明符;.1f为四舍五入到1位
        --> {1} 为第二个参数
    >>> a_dict
    {‘Name‘: ‘Sam‘, ‘Age‘: 18, ‘heigh‘: 65.55}
    >>> "{0[Name]}‘s heigh is {0[heigh]:.1f}KG.".format(a_dict)
    "Sam‘s heigh is 65.5KG."

其他字符串操作
    s.splitlines() --> 按行区分
    s.lower()   --> 小写字符转换
    s.count()  --> 字符个数统计
    >>> s = ‘‘‘Instance attribute dictionaries are avoided by creating
    ... class-level descriptors that intercept slot name access,and map
    ... those names to sequential storage apace in the instance.‘‘‘
    >>> s.splitlines()  -->  按行区分,返回列表
    [‘Instance attribute dictionaries are avoided by creating ‘, ‘class-level descriptors that intercept slot name access,and map‘, ‘those names to sequential storage apace in the instance.‘]
    >>> s.lower()   --> 小写字符转换
    ‘instance attribute dictionaries are avoided by creating \nclass-level descriptors that intercept slot name access,and map\nthose names to sequential storage apace in the instance.‘
    >>> print(s.lower())
    instance attribute dictionaries are avoided by creating
    class-level descriptors that intercept slot name access,and map
    those names to sequential storage apace in the instance.
    >>> s.lower().count(‘s‘)   --> 字符‘s‘出现的个数
    14
    >>>

字符串转换为字典
    >>> info = ‘name - sam / program - python / time - 2018‘
    >>> info_list = info.split(‘ / ‘)
    >>> print(info_list)
    [‘name - sam‘, ‘program - python‘, ‘time - 2018‘]
    >>> in_info_list = [x.split(‘ - ‘) for x in info_list]
    >>> print(in_info_list)
    [[‘name‘, ‘sam‘], [‘program‘, ‘python‘], [‘time‘, ‘2018‘]]
    >>> a_dict = dict(in_info_list)
    >>> print(a_dict)
    {‘name‘: ‘sam‘, ‘program‘: ‘python‘, ‘time‘: ‘2018‘}

字符串分片
    类似列表分片,返回一个新的字串
    >>> a_string = ‘Beginning Python:using Python 3.x.‘
    >>> a_string[0:5]
    ‘Begin‘
    >>> a_string[:10]
    ‘Beginning ‘
    >>> a_string[5:-5]
    ‘ning Python:using Python‘
    >>> a_string[:-5]
    ‘Beginning Python:using Python‘
    >>> a_string[9:]
    ‘ Python:using Python 3.x.‘

string  VS  bytes
    string:一个不可变(immutable)的unicode编码的字符序列
    bytes:一串由0 - 255 之间的数字序列组成的bytes 对象(ASCII 或是\x00 - \xff)
          bytes 对象是不可变的,可将bytes 对象转换为bytearray对象进行赋值(必须为0到255中的整数)
          可通过 + 连接bytes对象
          可通过下标取值(返回一个0到255中的整数)或len()计算bytes对象长度
    >>> bt = b‘acd‘     --> bytes 定义
    >>> type(bt)
    <class ‘bytes‘>
    >>> bt = b‘acd‘ + b‘\x98‘   --> bytes 使用 + 连接
    >>> bt
    b‘acd\x98‘
    >>> bt = b‘acd‘ + b‘b‘
    >>> bt
    b‘acdb‘
    >>> bt = bt + b‘\x99‘
    >>> bt
    b‘acdb\x99‘
    >>> len(bt)                 -->  bytes 对象长度计算
    5
    >>> bt[0]                   --> 通过索引下标取bytes对象的值
    97
    >>> bt[0] = 100             --> 不能直接对bytes对象赋值
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: ‘bytes‘ object does not support item assignment
    >>> btrr = bytearray(bt)    --> 将bytes对象转换为bytearray对象
    >>> btrr[0]
    97
    >>> btrr[0] = 100           --> 对bytearray对象直接赋值
    >>> btrr
    bytearray(b‘dcdb\x99‘)
    >>> bt
    b‘acdb\x99‘
    >>> type(btrr)              --> bytearray对象的类型
    <class ‘bytearray‘>
    >>> len(btrr)
    5
    >>> type(btrr)
    <class ‘bytearray‘>

string 和bytes 相互转换
    string      encode      bytes
    bytes       decode      string

    >>> a_string = ‘學習python‘
    >>> len(a_string)
    8
    >>> by = a_string.encode(‘utf-8‘)
    >>> by
    b‘\xe5\xad\xb8\xe7\xbf\x92python‘
    >>> len(by)
    12
    >>> by = a_string.encode(‘big5‘)
    >>> by
    b‘\xbe\xc7\xb2\xdfpython‘
    >>> len(by)
    10
    >>> roundtrip = by.decode(‘big5‘)
    >>> roundtrip
    ‘學習python‘
    >>> roundtrip == a_string
    True

原文地址:https://blog.51cto.com/sream/2379836

时间: 2024-08-04 00:53:16

Python 数据类型之字符串的相关文章

Python数据类型之字符串及其转义

字符串 与数字一样,字符串也是值,用单引号或双引号括起来. 'Hello world!' 或 "Hello world!" 字符串的转义 当我想在屏幕上输出 Let's go! 时可以这样写 print("Let's go!")>>> Let's go! 当输出内容有'时  可以用双引号来标识字符串的开始和结尾. 如果想输出在屏幕上的字符串中有双引号时,可以用单引号来标识字符串的开始和结尾. print(' "hello world!&q

Python数据类型-----数字&amp;字符串

Python数字类型 int类型表示的范围:-2147483648至2147483648之间,超出这个范围的数字即视为long(长整形) 在Python中不需要事先声明数据类型,它是根据具体的赋值来进行盘点数据类型的,例如: int类型 使用type(变量名) 可以查看该变量被赋值后的数据类型是什么 超出int范围的数字 int类型存储为long类型 只需要在后面加上大写字母L 在python中还支持复数类型 复数类型 Python字符串类型 # coding=UTF-8 #简单定义简单字符串

python数据类型和字符串(三)

一.变量 变量声明变量 #!/usr/bin/env python age=18 gender1='male' gender2='female' 变量作用:保存状态(程序的运行本质是一系列状态的变化,变量的目的就是用来保存状态,变量值的变化就构成了程序运行的不同结果.)例如:CS枪战,一个人的生命可以表示为life=active表示存活,当满足某种条件后修改变量life=inactive表示死亡. 变量命名规则遵循标识符命名规则,详见第二篇 name='lhf':'lhf'才是内存变量,name

python 数据类型一 字符串

包含了一系列的数据和操作这些数据的方法的一个整体,就叫作对象. 自行车 属性:手刹车,轮胎,脚踏板方法:如何前进的方法,控制停止的方法,控制方向 实际内容 男人与女人的恋爱男人与男人的恋爱女人与女人的恋爱 方法1:一见钟情 2.数据类型的组成 组成3部分.身份 id方法来看一看他的唯一标示符,内存地址靠这个哦!类型 type来看一看.值 数据项. 某书里的傲娇结论:python里一切都是指针,所以不用再考虑指针这个问题了! 3.常用基本数据类型.int 整型boolean 布尔string 字符

python数据类型之一字符串(str)

字符串是Python中最常用的数据类型之一,字符串的本质是值,就像数字一样 创建字符串的方式也很简单,只需为变量分配一个值即可 值的注意的是字符串是不可变量,不能被修改 在python3中所有的字符串均为Unicode字符串 栗子: var = 'Hello World!' 字符串格式化 字符串格式化使用字符串的格式化操作符即%来实现 格式化字符串的%s.%d.%.nf部分称之为转换说明符,标记了需要插入的转换值的位置 %s:格式化的部分为字符串str,如果不是字符串可以强制类型转换为字符串 %

Python基础-python数据类型之字符串(四)

字符串 字符串是python中常用的数据类型,使用('或")来创建. 创建字符串: 下标索引 字符串实际上是字符的数组,所以也支持索引. str1 = 'abcdef' 切片 定义:切片是指对操作的对象截取一部分的操作.字符串.列表.元祖都支持切片操作. 语法格式:[起始值:终值:步长] 附注:切片选取的区间属于左闭右开,即从'起始值'到'终值'的前一位(不包含终值本身) 如: 1 str1='abcdef' 2 print('str1[0:3]=',str1[0:3]) #取出 0~3 的字符

以写代学:python 数据类型之字符串,判断用户输入的id是否符合要求

字符串操作符 比较操作符:字符串大小按ASCLL码值大小进行比较 切片操作符:[].[:].[::] 成员关系操作符:in.not in 脚本:判断用户输入的id是否符合要求 #!/usr/bin/env python import string #定义字符的范围first_id = string.letters + "_"           //确定首字符的范围all_id = string.digits + first_id         //确定其他字符的范围 #请求用户输入

python数据类型之字符串

1.字符串概念 字符串:"abcd1234" 子字符串:"abc" 2.字符编码:ascii unicode utf8 python默认的文件编码是ascii,只能表示键盘上的数字,unicode是一个标准,能表示世界上所有的字符,utf8是Unicode的实现 3.字符串的len方法需注意字符的编码 >>> a = "1234" >>> len(a) 4 >>> a ="我是中国人

python数据类型:序列(字符串,元组,列表,字典)

序列通常有2个特点: 1,可以根据索引取值 2,可以切片操作 字符串,元组,列表,字典,都可以看做是序列类型 我的操作环境:Ubuntu16.04+python2.7 一.字符串类型 >按索引获取,索引从0开始 1 >>> name='ghostwu' 2 >>> name[0] 3 'g' 4 >>> name[1] 5 'h' 6 >>> name[6] 7 'u' 8 >>> >切片操作,第1个冒号