zoukankan      html  css  js  c++  java
  • python中字符串操作

    #创建字符串

    Str1 = 'Hello World'

    Str2 = "Let's go"

    #重复输入字符串

    print('hello' * 2)

    #字符串的切片

    print('helloworld'[2:])

    #格式化字符串

    print('%s is a good teacher'%'wade')

    #字符串的拼接

    方法一:

    a = '111'

    b = '222'

    c = '333'

    d = a + b + c

    print(c)            #111222333

    方法二:

    a = '111'

    b = '222'

    c = '333'

    c = 'xxx'.join([a,b,c])            #111xxx222xxx333     此方法较第一种方法效率高

    #字符串常用方法

    st = 'hello kitty'
    msg = "my name is {name},I'm {age} old"
    sp = '   happy life '

    print(st.count('l'))         #2     统计某元素个数(常用)
    print(st.capitalize())       #Hello kitty     首字母大写
    print(st.center(30,'-'))     #----------hello kitty----------     居中显示
    print(st.endswith('tty'))    #true     验证是否已某元素结尾,返回布尔值(常用)
    print(st.startswith('he'))   #true     验证是否已某元素开头,返回布尔值(常用)
    print(st.find('t'))          #8    查找到第一个元素,并将位置值返回(常用)
    print(msg.format(name='wade',age=30))     #my name is wade,I'm 30 old       格式化输入的另一种方式(常用)
    print(msg.format_map({name:'wade',age:20}))     #my name is wade,I'm 20 old       格式化输入的另一种方式
    print(st.index('i'))         #7    查找到第一个元素,并将位置值返回
    print('123.123'.isdigit())   #false     判断是否是一个整型数字
    print(st.islower())          #false     判断是否为全小写
    print(st.isupper())          #false     判断是否为全大写
    print('  ee'.isspace())      #false     判断是否为全空格
    print('This Title'.istitle())     #true     判断是否为标题(每个单词首字母大写)
    print('This Title'.lower())     #this title     将所有大写变小写(常用)
    print('This Title'.upper())     #THIS TITLE     将所有小写变大写(常用)
    print('This Title'.swapcase())     #tHIS tITLE     将大写变小写,小写变大写
    print(st.ljust(30,'*'))      #hello kitty******************      左对齐显现
    print(st.rjust(30,'*'))      #右对齐显示
    print(sp.strip())            #happy life      去除字符串两端的空格和换行符(常用)
    print(sp.lstrip())           #去除字符串左端的空格和换行符
    print(sp.rstrip())           #去除字符串右端的空格和换行符
    print(st.replace('kitty','wade'))     #hello wade     替换指定的字符串(常用)
    print(st.split(' '))         #['hello','kitty']     指定内容分割字符串(常用)
    print(st.title())            #Hello Title     将字符串变为标题格式,每个单词首字母大写

  • 相关阅读:
    stream流
    python笔记:str.contains小坑之 UserWarning To actually get the groups, use str.extract.
    获取excel的行索引值
    Pandas学习(4、数据载入、存储及文件格式
    python中如何压缩和解压缩文件
    保持服务器屏幕可控制状态
    python判断文件和文件夹是否存在、创建文件夹
    PDF处理
    selenium+python配置chrome浏览器的选项
    python实现复制粘贴
  • 原文地址:https://www.cnblogs.com/xjklmycw/p/8087080.html
Copyright © 2011-2022 走看看