Python string operations

Source: Internet
Author: User
A large collection of python string operations methods, including almost all common python string operations, such as string replacement, deletion, interception, replication, connection, comparison, search, and segmentation, for more information, see 1. remove spaces and special symbols

The code is as follows:

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


2. copy a string

The code is as follows:

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


3. connection string

The code is as follows:

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


4. search for characters

The code is as follows:

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


5. compare strings

The code is as follows:

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


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

The code is as follows:

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


7. string length

The code is as follows:

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


8. convert the case in the string

The code is as follows:

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

The code is as follows:

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


10. string-specific length comparison

The code is as follows:

# 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

The code is as follows:

# 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.

The code is as follows:

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


13. scan strings

The code is as follows:

# 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

The code is as follows:

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


15. search for strings

The code is as follows:

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


16. split the string

The code is as follows:

# 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

The code is as follows:

Delimiter = ','
Mylist = ['Brazil ', 'Russia', 'India ', 'China']
Print delimiter. join (mylist)


18. implementation of addslashes in PHP

The code is as follows:

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.

The code is as follows:

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

The code is as follows:

Str = '000000 ′
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

The code is as follows:

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

The code is as follows:

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

The code is as follows:

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.

The code is as follows:

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.

The code is as follows:

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.

The code is as follows:

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.

The code is as follows:

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

Once again, the String object cannot be changed. that is to say, after creating a string in python, you cannot change a part of the character. After any of the above functions change the string, a new string is returned, and the original string is not changed. In fact, this is also a work und. you can use the S = list (S) function to change S to a list with a single character as a member, in this way, you can use S [3] = 'a' to change the value, and then use S = "". restore join (S) to a string

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.