Python3菜鸟教程(4):字符串的操作和内置函数

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-29 23:11   65   0

参考链接

# -*-coding:UTF-8-*-


def basic_operator():
    # * + 操作
    str1 = 'hello'
    str2 = 'python'
    print(str1 + ' ' + str2) # hello python
    print(str1 * 2 + ' ' + str2 * 2) # hellohello pythonpython

    # 原始字符串输出
    str3 = 'pytho\n'
    str4 = r'pytho\n'
    print(str3)  # pytho 换行
    print(str4)  # python

    # 格式化字符串
    print('I am %s, I am %d years old' % ('张三', 100))  # 当用%格式化字符串时要用元组
    print('I am {:s}, I am {:d} years old'.format('张三', 10))

    # 对其格式化
    print('id'.ljust(10) + 'name'.ljust(10) + 'score'.ljust(10))
    all_info = [['12345678', 'Tom', 88], ['12345679', 'Jerry', 78.5]]

    for info in all_info:
        print('{:10s}{:10s}{:.1f}'.format(info[0], info[1], info[2]))


def build_in_function_test():
    # 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
    str1 = 'abcabc'
    cnt = str1.count('abc', 0, len(str1))
    print(cnt)

    # center, rjust, ljust 居中, 右,左填充
    print(str1.center(10, '*'))

    # find 在一个指定范围内查找子串,若存在则返回下标,否则-1
    print(str1.find('a', 0, 3))

    # index 和find一样, 但是如果不存在会返回一个异常 element = max(str) index = str.index(element)

    # strip、lstrip()、rstrip() 删除首位空格和左右空格
    print('   123  '.rstrip() + '|')

    # startwith
    print('abc123'.startswith('abc', 0, len('abc123')))
    print('abc123'.startswith('c1', 2, len('abc123')))

    # replace
    print('abcabc'.replace('a', 'A'))


if __name__ == '__main__':
    # basic_operator()
    build_in_function_test()
    # str1 = '12345'
    # str[2] = 'd'
    # TypeError: 'type' object does not support item assignment

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP