zoukankan      html  css  js  c++  java
  • Python学习笔记八:字符串的操作(二)

    1 #coding:utf-8
    2 #两个小函数
    3 #一、查找字符在字符串中第一次出现的位置.
    4  def find(string, char):
    5 index = 0
    6 while index < len(string):
    7 if (string[index] == char):
    8 return index
    9 index += 1
    10 return -1
    11
    12  #二、查找字符在字符串中的总数
    13  def findSum(string, char):
    14 index = 0
    15 count = 0
    16 while index < len(string):
    17 if (string[index] == char):
    18 count += 1
    19 index += 1
    20 return count
    21
    22  #使用以上两个函数
    23 print "字符1在字符串1211211234中第一次出现的位置: ", find("1211211234", "1")
    24 print "字符1在字符串1211211234中出现的次数:", findSum("1211211234", "1")
    25
    26 import string #引入string库
    27 print string.find('www.cctv.com', 'com') #result=9
    28 print string.find('Good','d') #result = 3
    29 print string.find('canada', 'a',2,9) #result =3,用法如下:
    30 #string.find(s, sub[, start[, end]])函数说明
    31 #Return the lowest index in s where the substring sub is found such that sub is
    32 #wholly contained in s[start:end]. Return -1 on failure. Defaults for start and
    33 #end and interpretation of negative values is the same as for slices.
    34 print string.lowercase #常量,abcdefghijklmnopqrstuvwxyz
    35 print string.uppercase #常量,ABCDEFGHIJKLMNOPQRSTUVWXYZ
    36 print string.digits #常量,0123456789
    37
    38 def isLower(char): #判断一个字符是否为小写
    39 if (string.find(string.lowercase, char) > -1):
    40 return 'Good'
    41 return 'bad'
    42 print isLower('S')
    43
    44 def isLowertest(char): #另外一种判断字符是否为小写的方法
    45 return char in string.lowercase
    46 print isLowertest('a')
    47
  • 相关阅读:
    【整理】PHP获取客户端真实IP地址详解
    配置百度编辑器变成纯代码编辑器
    Notepad++安装SVN插件
    【CodeBase】【转】php随机生成汉字
    【CodeBase】PHP打印所有用户自定义常量
    php5.3新垃圾回收机制详解
    php脚本cli 模式运行
    php 内存分配新
    php-fpm epoll封装
    火焰图定位dbproxy问题
  • 原文地址:https://www.cnblogs.com/dabiao/p/1683108.html
Copyright © 2011-2022 走看看