zoukankan      html  css  js  c++  java
  • Python3学习笔记-字符串和字符串操作

    字符串,可以存任意类型的字符串,比如名字,一句话等等

    name = 'Sriba'
    msg = 'Welcome to my blog.'

    字符串还有很多内置的方法,对字符串进行操作,常用的方法如下,下面注释带有是否的,返回的都是一个布尔值:

    name = 'my 	 name is {name},age is {age}.'
    print(name.capitalize()) # 大写
    print(name.center(50, '-')) # 50个-,把name放中间
    print(name.endswith('u')) # 是否以x结尾
    print(name.expandtabs(30)) # 补 的次数
    print(name.find('n')) # 查找字符串的索引
    print(name.format(name='niuniu', age=18)) # 这个是格式字符串
    print(name.format_map({'name': 'niuniu', 'age': 19})) # 这个也是格式化字符串,后面跟的是一个字典,字典在后面也会写
    print('abA123'.isalnum()) # 是否包含数字和字母
    print('abA'.isalpha()) # 是否是英文字母
    print('122'.isdigit()) # 是否是数字
    print('aa'.isidentifier()) # 是否是一个合法的变量名
    print('aa'.islower()) # 是否是小写字母
    print('AA'.isupper()) # 是否是大写字母
    print('Loadrunner Book'.istitle()) # 是不是一个标题,判断首字母是否大写
    print('+'.join(['hehe', 'haha', 'ee'])) # 拼接字符串
    print(name.lower()) # 变成小写
    print(name.upper()) # 变成大写
    print(' mysql '.lstrip()) # 默认去掉左边的空格和换行
    print(' mysql '.rstrip()) # 默认去掉右边的空格和换行
    print(' mysql '.strip()) # 默认去掉两边边的空格和换行
    p = str.maketrans('abcdefg', '1234567') # 前面的字符串和后面的字符串做映射
    print('cc ae gg'.translate(p)) # 输出按照上面maketrans做映射后的字符串
    # 下面是反解
    new_p = str.maketrans('1234567', 'abcdefg')
    print('cc ae gg'.translate(new_p))
    print('mysql is db.'.replace('mysql', 'oracle', 1)) # 替换字符串
    print('mysql is is db'.rfind('is')) # 返回最右边字符的下标
    print('1+2+3+4'.split('+')) # 切割字符串,返回一个list
    print('1+2+3 1+2+3+4'.splitlines()) # 按照换行符分割
    print('Abcdef'.swapcase()) # 大小写反转
  • 相关阅读:
    UVa 12174 (滑动窗口) Shuffle
    UVa 1607 (二分) Gates
    CodeForces ZeptoLab Code Rush 2015
    HDU 1525 (博弈) Euclid's Game
    HDU 2147 (博弈) kiki's game
    UVa 11093 Just Finish it up
    UVa 10954 (Huffman 优先队列) Add All
    CodeForces Round #298 Div.2
    UVa 12627 (递归 计数 找规律) Erratic Expansion
    UVa 714 (二分) Copying Books
  • 原文地址:https://www.cnblogs.com/fenggf/p/8886286.html
Copyright © 2011-2022 走看看