• Python——string


    字符串操作

    string典型的内置方法:

    • count()
    • center()
    • startswith()
    • find()
    • format()
    • lower()
    • upper()
    • strip()
    • replace()
    • split()
    • join()

    count()

    计数,查询字符串中出现指定字符的次数。

    1 st='hello kitty'
    2 
    3 print(st.count('l'))

    输出:2

    center()

    字符串居中。其中,50表示新字符串长度,'#'表示填充字符。

    1 st='hello kitty'
    2 print(st.center(50,'#'))

    输出:

    ###################hello kitty####################

    startswith()

    判断是否以某个内容开头。

    1 st='hello kitty'
    2 print(st.startswith('he'))

    输出:True

    find()

    查找到第一个元素,并将索引值返回。

    1 st='hello kitty'
    2 print(st.find('t')) 

    输出:8

    format()

    格式化输出的一种方式。(另一种方式在字符串中加%d、%s、%f,字符串外加%变量名)

    1 st='hello kitty {name} is {age}'
    2 print(st.format(name='alex',age=37))

    输出:

    hello kitty alex is 37

    lower()

    将字符串中的大写全部变成小写。

    1 print('My tLtle'.lower())

    输出:

    my tltle

    upper()

    将字符串中的小写全部变成大写。

    1 print('My tLtle'.upper())

    输出:

    MY TLTLE

    strip()

    将字符串中的制表符、换行符等不可见字符去掉。

    1 print('	My tLtle
    '.strip())

    输出:

    My tLtle

    replace()

    将字符串中第1个'itle'替换为'lesson'。

    1 print('My title title'.replace('itle','lesson',1))

    输出:

    My tlesson title

    split()

     以字符串中的第1个i为分隔符,将字符串分割为两部分,并放入列表中。

    1 print('My title title'.split('i',1))

    输出:

    ['My t', 'tle title']

    详细解释:

    join()

    字符串拼接最好的方法。需要注意的是,join()中必须是一个列表。

    1 str1 = 'Alex'
    2 str2 = 'Oliver'
    3 a = ''.join([str1,' and ',str2])
    4 print(a)

    输出:

    Alex and Oliver

    Python查看帮助的方法

    >>> help(str) 

    >>> help(str.split)

    >>> help(int)

    小练习

    统计str字符串中每个字符的个数并打印。

    str = 'U2FsdGVkX1+xaZLZ3hGZbZf40vPRhk+j+FHIHiopidA8GG6aolpjAU7kVHuLMYcJ'
    1 # 方法1:
    2 b = {}
    3 for i in str:
    4     if i in b:
    5         b[i] += 1
    6     else:
    7         b.setdefault('%s'%i,1)
    8 for i,v in b.items():
    9     print("字符串:%s,个数:%d"%(i,v))
    1 #方法2
    2 dic = {}
    3 for i in str:
    4     if i in dic:continue
    5     else:
    6         dic.setdefault(i,str.count(i))
    7         print(i,str.count(i))
  • 相关阅读:
    rhel5.4 x64安装apache http server2.2.27,并创建自动启服务
    解决BEA-000438 Unable to load performance pack.
    为aix系统挂载iso镜像-命令
    IBM小型机创建RAID
    linux下使用parted工具划分大于2T的分区
    linux下的SElinux
    日立HDS AMS2100存储的调试
    rhel创建yum源
    rfid安全简介
    安卓模拟器抓包
  • 原文地址:https://www.cnblogs.com/pyramid1001/p/5803278.html
Copyright © 2020-2023  润新知