• python 字符串操作


    string的常用操作:

    1 # 重复输出字符串
    2 print('hello'*2)   # 输出两遍
    3 
    4 # 2 [] , [:]  通过索引获取字符串中字符,和列表的切片操作相同
    5 print('hellowworld'[3:])
    6 
    7 # 关键字 in
    8 print('e2l' in 'hellow')  #判断‘e2l’是不是在‘hellow’中,在输出True,否则False
    输出:hellohello
       lowworld
        False
    1 # 格式字符串
    2 name = input("Name:")
    3 print('%s is a good student'%name)
    输入:Name:双双小可爱
    输出:双双小可爱 is a good student
     1      # 字符串的拼接
     2 a = '123'
     3 b = '235'
     4 
     5 # 法一(落后)
     6 n = a+b
     7 print(n)
     8 
     9 #法二 通过‘’里的对象把两个字符串连接起来
    10 c = ''.join([a, b])
    11 d = '**'.join([a, b])
    12 print(c, d)
    输出:123235
         123235 123**235
     1            #string的内置方法
     2 st = 'hello 	kitty {name} is {age}'
     3 
     4 print(st.count('l'))                #  统计元素个数
     5 print(st.capitalize())              #  首字母大写
     6 print(st.center(19,'*'))            #  居中(''里面可以是空格或者其他符号)
     7 print(st.endswith('ll'))            #  以某个内容结尾
     8 print(st.startswith('he'))          #  以某内容开始
     9 print(st.expandtabs(tabsize=20))    #  设置	的空格
    10 print(st.find('l'))        #  查找某个元素的第一个位置,并将索引值返回
    11 print(st.format(name = 'tom', age = '22'))      #  格式输出,通过name赋值
    12 print(st.format_map({'name':'tom','age':'22'})) #  同上,通过字典的方式赋值赋值
    13 print(st.index('l'))               #  查找某个元素的索引,如没有则返回-1
    输出:2
        Hello 	kitty {name} is {age}
    hello kitty {name} is {age} False True hello kitty {name} is {age} 2 hello kitty tom is 22 hello kitty tom is 22 2
     1 print('abc123'.isalnum())   #  判断字符串是不是一个包含数字和字母
     2 print('12'.isdecimal())     #  判断是不是十进制的数
     3 print('12.35'.isdigit())    #  判断是不是一个整型
     4 print('1abc'.isidentifier())  #  判断是不是非法字符
     5 print('Abc'.islower())    #  判断是不是全小写
     6 print('ABC'.isupper())    #  判断是不是全大写
     7 print(' '.isspace())    #  判断是不是空格
     8 print('My Girl'.istitle())    #  判断是不是标题(每个单词的首字母大写)
     9 print('My Girl'.lower())    #  大写变小写
    10 print('My Girl'.upper())    #  小写变大写
    11 print('My Girl'.swapcase()) #  大小写反转
    12 print('	My Girl
    '.strip())    #  去掉字符串的特殊字符
    13 print('	My Girl
    '.lstrip())    #  去掉字符串左边的特殊字符
    14 print('	My Girl
    '.rstrip())    #  去掉字符串右边的特殊字符
    15 print('My Girl'.replace('Girl','boy'))    #  替换 Girl--->boy
    16 print('My Girl Girl'.replace('Girl','boy',1))    #  替换 Girl--->boy,替换一次
    输出:True
        True
        False
        False
        False
        True
        True
        True
        my girl
        MY GIRL
        mY gIRL
        My Girl
        My Girl
    
        	    My Girl
        My boy
        My boy Girl
    1 print('My Girl'.split(' '))    #  分割,以空格为分界线
    输出:['My', 'Girl']

  • 相关阅读:
    悬浮按钮
    C语言学习笔记
    python3之环境搭建以及基础语法
    设计模式之单例模式
    浅谈vuex
    用位运算替代js中的常见操作
    浅析Symbol
    egg.js源码解析之render()
    js的事件循环机制和任务队列
    浅谈js异步
  • 原文地址:https://www.cnblogs.com/ss-long/p/10291642.html
Copyright © 2020-2023  润新知