Python string study notes

Source: Internet
Author: User
Tags explode php explode print format strlen uppercase letter


String formatting:

Format = "hello % s, % s enough for ya ?"
Values = ('world', 'Hot ')
Print format % values
Result: hello world, hot enough for ya?

Note: If it is not executed in the command line, enclose the brackets behind print.

Similar to php but with different function or method names:

Explode/"target =" _ blank "> php explode => python split
Php trim => python strip
Php implode => python join


1. Remove spaces and special symbols

: S. strip (). lstrip (). rstrip (',')

2. Copy a string

: # Strcpy (sStr1, sStr2)
SStr1 = 'strcpy'
SStr2 = sStr1
SStr1 = 'strcp2'
Print sStr2

3. Connection string

: # Strcat (sStr1, sStr2)
SStr1 = 'strcat'
SStr2 = 'append'
SStr1 + = sStr2
Print sStr1

4. Search for characters

: # Strchr (sStr1, sStr2)
#<0 is not found
SStr1 = 'strchr'
SStr2 ='s'
NPos = sStr1.index (sStr2)
Print nPos

5. Compare strings

: # Strcmp (sStr1, sStr2)
SStr1 = 'strchr'
SStr2 = 'strch'
Print cmp (sStr1, sStr2)

6. Check whether the scan string contains the specified characters.

: # Strspns (sStr1, sStr2)
SStr1 = '123'
SStr2 = '123'
# SStr1 and chars both in sStr1 and sStr2
Print len (sStr1 and sStr2)

7. String length

: # Strlen (sStr1)
SStr1 = 'strlen'
Print len (sStr1)

8. Convert the case in the string

: S. lower () # lower case
S. upper () # uppercase
S. swapcase () # case-insensitive swap
S. capitalize () # uppercase letters
String. capwords (S) # This is the method in the module. It separates S with the split () function, converts the first letter into upper-case letters with capitalize (), and finally merges them with join ().
# Instance:
# Strlwr (sStr1)
SStr1 = 'jcstrlwr'
SStr1 = sStr1.upper ()
# SStr1 = sStr1.lower ()
Print sStr1


9. Append a string of the specified length

: # Strncat (sStr1, sStr2, n)
SStr1 = '123'
SStr2 = 'abcdef'
N = 3
SStr1 + = sStr2 [0: n]
Print sStr1

10. String-specific length comparison

: # Strncmp (sStr1, sStr2, n)
SStr1 = '123'
SStr2 = '123bc'
N = 3
Print cmp (sStr1 [0: n], sStr2 [0: n])

11. Copy characters of the specified length

: # Strncpy (sStr1, sStr2, n)
SStr1 =''
SStr2 = '123'
N = 3
SStr1 = sStr2 [0: n]
Print sStr1

12. Replace the first n characters of the string with the specified characters.

: # Strnset (sStr1, ch, n)
SStr1 = '123'
Ch = 'R'
N = 3
SStr1 = n * ch + sStr1 [3:]
Print sStr1

13. Scan strings

: # Strpbrk (sStr1, sStr2)
SStr1 = 'cekjgdklab'
SStr2 = 'gka'
NPos =-1
For c in sStr1:
If c in sStr2:
NPos = sStr1.index (c)
Break
Print nPos

14. Flip string

: # Strrev (sStr1)
SStr1 = 'abcdefg'
SStr1 = sStr1 [:-1]
Print sStr1

15. Search for strings

: # Strstr (sStr1, sStr2)
SStr1 = 'abcdefg'
SStr2 = 'Cde'
Print sStr1.find (sStr2)

16. Split the string

: # Strtok (sStr1, sStr2)
SStr1 = 'AB, cde, fgh, ijk'
SStr2 = ','
SStr1 = sStr1 [sStr1.find (sStr2) + 1:]
Print sStr1
# Or
S = 'AB, cde, fgh, ijk'
Print (s. split (','))

17. Connection string

: Delimiter = ','
Mylist = ['Brazil ', 'Russia', 'India ', 'China']
Print delimiter. join (mylist)
18. Implementation of addslashes in PHP
: Def addslashes (s ):
D = {'"': '\"', "'": "\'", "\ 0": "\ 0 ","\\": "\\\\"}
Return ''. join (d. get (c, c) for c in s)

S = "John 'Johnny 'Doe (a.k. a. \" Super Joe \ ") \ 0"
Print s
Print addslashes (s)

19. Only letters and numbers are displayed.

: Def OnlyCharNum (s, oth = ''):
S2 = s. lower ();
Fomart = 'abcdefghijklmnopqrstuvwxyz0123456789'
For c in s2:
If not c in fomart:
S = s. replace (c ,'');
Return s;

Print (OnlyStr ("a000 aa-B "))

20. Truncate a string

: Str = '2017 & prime;
Print str [0: 3] # capture the first to third characters
Print str [:] # capture all characters in a string
Print str [6:] # truncates the seventh character to the end
Print str [:-3] # capture the first to last three characters
Print str [2] # truncate the third character
Print str [-1] # capture the first to last character
Print str [:-1] # Create a string in the opposite order of the original string
Print str [-3:-1] # extract the characters before the last and last digits
Print str [-3:] # truncate the last third digit to the end
Print str [:-5:-3] # reverse truncation. What do you mean?

21. Alignment of strings in output

: S. ljust (width, [fillchar])
# The output width is a string of characters, and the S is left aligned. The missing part is filled with fillchar. The default value is space.
S. Align UST (width, [fillchar]) # right alignment
S. center (width, [fillchar]) # center alignment
S. zfill (width) # converts S to width length and alignment right. Fill the remaining part with 0.

22. Search and replace strings

: S. find (substr, [start, [end])
# Return the number of the first letter of substr in S. If S does not contain substr,-1 is returned. The functions of start and end are equivalent to searching in S [start: end].
S. index (substr, [start, [end])
# It is the same as find (), but a runtime error is returned when S does not contain substr.
S. rfind (substr, [start, [end])
# Return the number of the first letter of the last occurrence of substr in S. If there is no substr in S,-1 is returned, that is, the first letter of the first occurrence of substr from the right.
S. rindex (substr, [start, [end])
S. count (substr, [start, [end]) # calculate the number of times that substr appears in S
S. replace (oldstr, newstr, [count])
# Replace oldstar with newstr in S, and count with the number of replicas. This is a common form of replacement, and some functions replace special characters.
S. strip ([chars])
# Remove all characters in chars before and after S, which can be understood as replacing chars before and after S with None
S. lstrip ([chars])
S. rstrip ([chars])
S. expandtabs ([tabsize])
# Replace the tab character in S with no space. Each tab is replaced with tabsize with eight spaces by default.
23. String segmentation and combination
: S. split ([sep, [maxsplit])
# Use sep as the separator to divide S into a list. Maxsplit indicates the number of splits. The default delimiter is a blank character.
S. rsplit ([sep, [maxsplit])
S. splitlines ([keepends])
# Divides S into a list according to the row delimiter, and keepends is a bool value. If it is true, the row delimiter is retained.
S. join (seq) # concatenates the sequence represented by seq, namely the string sequence, with S

24. String mapping. This function contains two functions.

: String. maketrans (from,)
# Returns a 256-character translation table, where the characters in from are converted to, so the from and to must be of the same length.
S. translate (table [, deletechars])
# Use the post-production translation table of the above function to translate S and delete some characters in deletechars. Note that if S is a unicode string, the deletechars parameter is not supported. You can translate a character into None to achieve the same function. In addition, you can use the functions of the codecs module to create more powerful translation tables.
.
25. A string also has a pair of encoding and decoding functions.

: S. encode ([encoding, [errors])
# Encoding can have multiple values, such as gb2312 gbk gb18030 bz2 zlib big5 bzse64. The default errors value is "strict", which means UnicodeError. Possible values include 'ignore', 'replace ', 'xmlcharrefresh', 'backslashreplace', and all values registered through codecs. register_error. This part of content involves the codecs module, not the plain white
S. decode ([encoding, [errors])

26. Test and judgment functions of strings. These functions are not in the string Module and return bool values.

: S. startswith (prefix [, start [, end])
# Whether to start with prefix
S. endswith (suffix [, start [, end])
# End with suffix
S. isalnum ()
# Whether it is all letters and numbers with at least one character
S. isalpha () # whether it is all letters with at least one character
S. isdigit () # whether it is all numbers with at least one character
S. isspace () # whether it is all blank characters with at least one character
S. islower () # are all lowercase letters in S?
S. isupper () # Is the uppercase letter in S?
S. istitle () # whether S is capitalized

27. string type conversion functions. These functions are only available in the string Module.

: String. atoi (s [, base])
# Base is 10 by default. If it is 0, s can be a string in the format of 012 or 0x23. If it is 16, s can only be a string in the format of 0x23 or 0X12.
String. atol (s [, base]) # Convert it to long
String. atof (s [, base]) # Convert to float

28. Python string inversion

For the str type, python does not have the reverse function. However, we can efficiently reverse a string by performing reverse-step slicing.

S = 'ABCDE'
S [:-1]

Related Article

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.