zoukankan      html  css  js  c++  java
  • Python 学习笔记【11】字符串操作

      capitalize /count /center / endswith /expandtabs / find

    1 name = "my name is alex"
    2 
    3 print(name.capitalize())  # 首字母大写
    4 print(name.count("a"))  # 统计字母个数
    5 print(name.center(50, "-"))  # 打印50个字符,name放中间,空缺的部分用 "-" 补全
    6 print(name.endswith("ex"))  # 判断字符串以什么结尾,返回逻辑值
    7 print(name.expandtabs(30))  # 把tab键(	)转换为30个空格
    8 print(name.find("name"))  # 查找字符的索引位置
    9 print(name[name.find("name"):9])  # 字符串也可以切片

       format / format_map

    1 name = "my name is {name} and i am {year} old."
    2 
    3 print(name.format(name="alex", year=23))
    4 print(name.format_map({'name': 'alex', 'year': 12}))

       isalnum / isalpha / isdigit /isidentifier / islower / isspace / istitle / isprintable / isupper

    1 print('abc123'.isalnum())  # 是否是数字或字母
    2 print('abc'.isalpha())  # 是否是纯英文字符
    3 print('123'.isdigit())  # 是否是一个整数
    4 print('a1A'.isidentifier())  # 判断是不是一个合法的标识符
    5 print('amen'.islower())  # 判断是否是小写
    6 print('  '.isspace())  # 判断是否是空格
    7 print('My Name Is'.istitle())  # 判断是否是标题
    8 print('abc'.isprintable())  # 是否可打印,如tty file, drive file 是不能打印的
    9 print('ABC'.isupper())  # 是否全是大写

      join / ljust / rjust / lower / upper / lstrip / rstrip / strip

     1 print('+'.join(['1', '2', '3']))
     2 
     3 print(name.ljust(50, '*'))  # 打印50个字符,name放前面,空缺的部分用 "*" 补全
     4 print(name.rjust(50, '*'))  # 打印50个字符,name放后面,空缺的部分用 "*" 补全
     5 
     6 print('Alex'.lower())  # 把大写变成小写
     7 print('Alex'.upper())  # 把小写变成大写
     8 
     9 print('
    Alex
    '.lstrip())  # 从左边去掉空格和回车
    10 print('
    Alex
    '.rstrip())  # 从右边去掉空格和回车
    11 print('
    Alex
    '.strip())  # 去掉空格和回车

      maketrans

    1 p = str.maketrans("abcdefg", '!@#¥%&*')  # 把前面的字符串转成后面对应的字符串
    2 
    3 print("alex li".translate(p))

      replace / rfind / split / splitlines / ewapcase / zfill

    1 print('alex li'.replace('l', 'L', 1))  # 把第一个l替换成大写的L
    2 print('alex li'.rfind('l'))  # 从左往右数,找到最右边的‘l’.返回下标
    3 print('1+2+3+4'.split('+'))  # 用'+'分割字符后,提取其他字符
    4 print('1
    +2
    +3
    +4
    '.splitlines())   # 用'换行'分割字符后,提取其他字符。效果同 .split(
    ),可识别不同系统的换行
    5 print("Alex li".swapcase())  # 大写变小写,小写变大写
    6 print('alex li'.zfill(50))  # 打印50个字符,alex li放后面,空缺的部分用 "0" 补全
  • 相关阅读:
    获取指定路径下的文件夹及文件名称
    Unity3D两种方式实现游戏视频播放
    Unity Steam_VR Camera
    Unity Steam_VR 开发工具插件 VRTK自带案例分析(第一部分)
    Unity Steam_VR 开发工具插件 VRTK自带案例分析(第二部分)
    weblogic安装注意事项_linux
    从英文变形规则计算到Restful Api设计
    如何正确使用Cocoapods
    clang -rewrite-objc的使用点滴
    kubernetes听云实战发布版
  • 原文地址:https://www.cnblogs.com/a1-code/p/6008266.html
Copyright © 2011-2022 走看看