Python study note 8: String operations (2)

Source: Internet
Author: User

 

 1 # coding: UTF-8
2 # two small Functions
3 #1. Search for the position where the character first appears in the string.
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 #2. Search for the total number of characters in the string
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 # use the above two functions
23 print "position where character 1 appears for the first time in string 1211211234:", find ("1211211234", "1 ")
24 print "Number of times character 1 appears in string 1211211234:", findsum ("1211211234", "1 ")
25
26 Import string # introduce the string Library
27 print string. Find ('www .cctv.com ', 'com') # result = 9
28 print string. Find ('good', 'D') # result = 3
29 print string. Find ('Canada ', 'A',) # result = 3. The usage is as follows:
30 # string. Find (S, sub [, start [, end]) Function Description
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 # constant, abcdefghijklmnopqrstuvwxyz
35 print string. uppercase # constant, abcdefghijklmnopqrstuvwxyz
36 print string. digits # constant, 0123456789
37
38 def isLower (char): # determines whether a character is in lowercase.
39 if (string. find (string. lowercase, char)>-1 ):
40 return 'good'
41 return 'bad'
42 print isLower ('s ')
43
44 def isLowertest (char): # Another method to determine whether the character is lowercase
45 return char in string. lowercase
46 print isLowertest ('A ')
47

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.