zoukankan      html  css  js  c++  java
  • Python3中操作字符串str必须记住的几个方法

    几个Python的字符串常用内建函数

    1.方法:Python3 isdigit()方法

     描述:Python isdigit() 方法检测字符串是否只由数字组成。

     语法:str.isdigit()

     参数:无

     返回值:如果字符串只包含数字则返回 True 否则返回 False。

     实例:

     1 str = "123456"; 
     2 print (str.isdigit())
     3 
     4 str = "abcdef"
     5 print (str.isdigit())
     6 
     7 
     8 # 输出结果
     9 True
    10 False

    2.方法:Python3 replace()方法

     描述:replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

     语法:str.replace(old, new[, max])

     参数:

    • old -- 将被替换的子字符串。
    • new -- 新字符串,用于替换old子字符串。
    • max -- 可选字符串, 替换不超过 max 次

     返回值:返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。

     实例:

     1 str = "www.w3cschool.cc"
     2 print ("菜鸟教程旧地址:", str)
     3 print ("菜鸟教程新地址:", str.replace("w3cschool.cc", "runoob.com"))
     4 
     5 str = "this is string example....wow!!!"
     6 print (str.replace("is", "was", 3))
     7 
     8 
     9 # 输出结果
    10 菜鸟教程旧地址: www.w3cschool.cc
    11 菜鸟教程新地址: www.runoob.com
    12 thwas was string example....wow!!!

    3.方法:Python3 find()方法

     描述:find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。

     语法:str.find(str, beg=0, end=len(string))

     参数:

    • str -- 指定检索的字符串
    • beg -- 开始索引,默认为0。
    • end -- 结束索引,默认为字符串的长度。

     返回值:如果包含子字符串返回开始的索引值,否则返回-1。

     实例:

     1 str1 = "Runoob example....wow!!!"
     2 str2 = "exam";
     3  
     4 print (str1.find(str2))
     5 print (str1.find(str2, 5))
     6 print (str1.find(str2, 10))
     7 
     8 # 输出结果
     9 7
    10 7
    11 -1

     扩展实例(Python 3.0+):

     1 # 实例(Python 3.0+)
     2 
     3 >>>info = 'abca'
     4 >>> print(info.find('a'))      # 从下标0开始,查找在字符串里第一个出现的子串,返回结果:0
     5 0
     6 >>> print(info.find('a', 1))   # 从下标1开始,查找在字符串里第一个出现的子串:返回结果3
     7 3
     8 >>> print(info.find('3'))      # 查找不到返回-1
     9 -1
    10 >>>

    4.方法:Python3 count()方法

     描述:count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

     语法:str.count(sub, start= 0,end=len(string))

     参数:

    • sub -- 搜索的子字符串
    • start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
    • end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。

     返回值:该方法返回子字符串在字符串中出现的次数。

     实例:

     1 str="www.runoob.com"
     2 sub='o'
     3 print ("str.count('o') : ", str.count(sub))
     4 
     5 sub='run'
     6 print ("str.count('run', 0, 10) : ", str.count(sub,0,10))
     7 
     8 
     9 # 输出结果
    10 str.count('o') :  3
    11 str.count('run', 0, 10) :  1

    5.方法:Python3 strip()方法

     描述:Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。

     语法:str.strip([chars]);

     参数:

    • chars -- 移除字符串头尾指定的字符。

     返回值:返回移除字符串头尾指定的字符生成的新字符串。

     实例:

    1 str = "*****this is string example....wow!!!*****"
    2 print (str.strip( '*' ))
    3 
    4 
    5 # 输出结果
    6 this is string example....wow!!!

    6.方法:Python3 split()方法

     描述:split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串

     语法:str.split(str="", num=string.count(str))

     参数:

    • str -- 分隔符,默认为所有的空字符,包括空格、换行( )、制表符( )等。
    • num -- 分割次数。

     返回值:返回分割后的字符串列表。

     实例:

     1 str = "this is string example....wow!!!"
     2 print (str.split( ))
     3 print (str.split('i',1))
     4 print (str.split('w'))
     5 
     6 
     7 # 输出结果
     8 ['this', 'is', 'string', 'example....wow!!!']
     9 ['th', 's is string example....wow!!!']
    10 ['this is string example....', 'o', '!!!']

    7.方法:Python3 center()方法

     描述:center() 方法返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。

     语法:str.center(width[, fillchar])

     参数:

    • width -- 字符串的总宽度。
    • fillchar -- 填充字符。

     返回值:返回一个指定的宽度 width 居中的字符串,如果 width 小于字符串宽度直接返回字符串,否则使用 fillchar 去填充。

     实例:

    1 str = "[www.runoob.com]"
    2 
    3 print ("str.center(40, '*') : ", str.center(40, '*'))
    4 
    5 
    6 # 输出结果
    7 str.center(40, '*') :  ************[www.runoob.com]************

    8.方法:Python3 join()方法

     描述:Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

     语法:str.join(sequence)

     参数:

    • sequence -- 要连接的元素序列。

     返回值:返回通过指定字符连接序列中元素后生成的新字符串。

     实例:

     1 s1 = "-"
     2 s2 = ""
     3 seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
     4 print (s1.join( seq ))
     5 print (s2.join( seq ))
     6 
     7 
     8 # 输出结果
     9 r-u-n-o-o-b
    10 runoob

    9.方法:Python3 maketrans()方法

     描述:

    1. maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
    2. 两个字符串的长度必须相同,为一一对应的关系。

       注:Python3.4已经没有string.maketrans()了,取而代之的是内建函数: bytearray.maketrans()、bytes.maketrans()、str.maketrans()

     语法:str.maketrans(intab, outtab)

     参数:

    • intab -- 字符串中要替代的字符组成的字符串。
    • outtab -- 相应的映射字符的字符串。

     返回值:返回字符串转换后生成的新字符串。

     实例:

     1 intab = "aeiou"
     2 outtab = "12345"
     3 trantab = str.maketrans(intab, outtab)
     4 
     5 str = "this is string example....wow!!!"
     6 print (str.translate(trantab))
     7 
     8 
     9 # 输出结果
    10 th3s 3s str3ng 2x1mpl2....w4w!!!

    10.方法:Python3 translate()方法

      描述:translate() 方法根据参数table给出的表(包含 256 个字符)转换字符串的字符,要过滤掉的字符放到 deletechars参数中。

      语法:

    • str.translate(table[, deletechars]);
    • bytes.translate(table[, delete])
    • bytearray.translate(table[, delete])

      参数:

    • table -- 翻译表,翻译表是通过 maketrans() 方法转换而来。
    • deletechars -- 字符串中要过滤的字符列表。

      返回值:返回翻译后的字符串,若给出了 delete 参数,则将原来的bytes中的属于delete的字符删除,剩下的字符要按照table中给出的映射来进行映射 。

      实例:

    实例(Python 3.0+)
     1 intab = "aeiou"
     2 outtab = "12345"
     3 trantab = str.maketrans(intab, outtab)   # 制作翻译表
     4  
     5 str = "this is string example....wow!!!"
     6 print (str.translate(trantab))
     7 
     8 
     9 # 输出结果
    10 th3s 3s str3ng 2x1mpl2....w4w!!!

      实例:演示过滤掉字符'o'

    1 # 制作翻译表
    2 bytes_tabtrans = bytes.maketrans(b'abcdefghijklmnopqrstuvwxyz', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    3  
    4 # 转换为大写,并删除字母o
    5 print(b'runoob'.translate(bytes_tabtrans, b'o'))
    6 
    7 
    8 # 输出结果
    9 b'RUNB'

    11.方法:Python format 格式化函数

      描述:

    1. Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
    2. 基本语法是通过 {} 和 : 来代替以前的 % 。
    3. format 函数可以接受不限个参数,位置可以不按顺序。

      

    实例
     1 >>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
     2 'hello world'
     3  
     4 >>> "{0} {1}".format("hello", "world")  # 设置指定位置
     5 'hello world'
     6  
     7 >>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
     8 'world hello world'
     9 
    10 >>> 

      也可以设置参数:

    实例
     1 # -*- coding: UTF-8 -*-
     2  
     3 print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
     4  
     5 # 通过字典设置参数
     6 site = {"name": "菜鸟教程", "url": "www.runoob.com"}
     7 print("网站名:{name}, 地址 {url}".format(**site))
     8  
     9 # 通过列表索引设置参数
    10 my_list = ['菜鸟教程', 'www.runoob.com']
    11 print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的
    12 
    13 
    14 # 输出结果
    15 网站名:菜鸟教程, 地址 www.runoob.com
    16 网站名:菜鸟教程, 地址 www.runoob.com
    17 网站名:菜鸟教程, 地址 www.runoob.com

      也可以向str.format() 传入对象

    实例
     1 # -*- coding: UTF-8 -*-
     2  
     3 class AssignValue(object):
     4     def __init__(self, value):
     5         self.value = value
     6 my_value = AssignValue(6)
     7 print('value 为: {0.value}'.format(my_value))  # "0" 是可选的
     8 
     9 
    10 # 输出结果
    11 value 为: 6

      数字格式化

      下表展示了 str.format() 格式化数字的多种方法:

    1 >>> print("{:.2f}".format(3.1415926));
    2 3.14
    数字格式输出描述
    3.1415926 {:.2f} 3.14 保留小数点后两位
    3.1415926 {:+.2f} +3.14 带符号保留小数点后两位
    -1 {:+.2f} -1.00 带符号保留小数点后两位
    2.71828 {:.0f} 3 不带小数
    5 {:0>2d} 05 数字补零 (填充左边, 宽度为2)
    5 {:x<4d} 5xxx 数字补x (填充右边, 宽度为4)
    10 {:x<4d} 10xx 数字补x (填充右边, 宽度为4)
    1000000 {:,} 1,000,000 以逗号分隔的数字格式
    0.25 {:.2%} 25.00% 百分比格式
    1000000000 {:.2e} 1.00e+09 指数记法
    13 {:10d}         13 右对齐 (默认, 宽度为10)
    13 {:<10d} 13 左对齐 (宽度为10)
    13 {:^10d}     13 中间对齐 (宽度为10)
    11
    '{:b}'.format(11)
    '{:d}'.format(11)
    '{:o}'.format(11)
    '{:x}'.format(11)
    '{:#x}'.format(11)
    '{:#X}'.format(11)
    1011
    11
    13
    b
    0xb
    0XB
    进制
    1. ^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。
    2. + 表示在正数前显示 +,负数前显示 -;  (空格)表示在正数前加空格
    3. b、d、o、x 分别是二进制、十进制、八进制、十六进制。

      此外我们可以使用大括号 {} 来转义大括号,如下实例:

    实例
    1 # -*- coding: UTF-8 -*-
    2  
    3 print ("{} 对应的位置是 {{0}}".format("runoob"))
    4 
    5 
    6 # 输出结果
    7 runoob 对应的位置是 {0}

      以上内容摘至菜鸟教程,为学习Python中字符串常用内建函数的学习笔记,仅供参考,如存在错误请指出,万分感谢!

      以上仅为Python中字符串部分常用内建函数,更多字符串内建函数请参阅菜鸟教程-http://www.runoob.com/python3/python3-string.html

  • 相关阅读:
    readystatechange事件
    DOMContentLoaded事件
    beforeunload事件
    jieba
    模型评估
    机器学习术语
    决策树
    kafka
    即时通讯好文
    HTTP头的Expires与Cache-control
  • 原文地址:https://www.cnblogs.com/AiyaFocus/p/8407183.html
Copyright © 2011-2022 走看看