python从小白到入门(4)

    技术2022-07-13  66

    1、字符串: 列表、字符串、元组都可以进行索引,字符串和元组不能进行增删改查。 2.replace替换。

    >>> str_a = "this is python string" >>> str_a.replace('t', 'T') 'This is pyThon sTring' >>> #replace 替换,并没有改变原来的字符串,只是返回一个新的字符串 >>> #如果不赋值给一个变量,只是出现一次,因为没有一个变量去引用它

    3、upper() 将字符串字母全部大写,lower()将字符串中字母全部变为小写。capitalize()将首字母变为大写(还有很多方法在字符串方法文档中)。 4、split()切割。

    >>> str_a.split() ['this', 'is', 'python', 'string'] >>> #字符串切割 >>> #默认以空格分开 >>> str_a.split('i') ['th', 's ', 's python str', 'ng'] >>> str_a.split('i', 1) ['th', 's is python string'] >>> #1表示切割次数 >>> '*'.join(str_a.split('i', 2)) 'th*s *s python string' >>> #与join连用

    5、find()查找字母位置。

    >>> str_a.find('i') 2 >>> #字符串查找字母位置 >>> #查找元素在字符串中的起始值 >>> str_a.find('i', 10) 18 >>> #10表示从位置10开始查找,如果没有返回-1,不会报错

    6、isalpha()判断是不是全为字母,isdigit()判断是不是全为数字,islower()、isupper()判断是不是全为小写和大写。 7、\n 换行,\t 缩进 相当于TAB, \b 退一格,\取消转义(一般用于表示路径), \0表示空格, \a 提示音。 8、

    >>> '缔凡'.encode(encoding='utf8') b'\xe7\xbc\x94\xe5\x87\xa1' >>> '缔凡'.encode(encoding='gbk') b'\xb5\xde\xb7\xb2' >>> #转换为指定编码 >>> bstring = '缔凡'.encode(encoding='utf8') >>> bstring b'\xe7\xbc\x94\xe5\x87\xa1' >>> bstring.decode('utf8') '缔凡' >>> #也可以用decode转换为汉字
    Processed: 0.009, SQL: 9