This article describes in detail common operations on python strings, such as string replacement, deletion, interception, replication, connection, comparison, search, and splitting, for more information about how to operate python strings, see the examples in this article.
1. remove spaces
Str. strip ():Delete the specified characters on both sides of the string, and write the specified characters in parentheses. the default value is space.
>>> a=' hello '>>> b=a.strip()>>> print(b)hello
Str. lstrip ():Delete the specified character on the left of the string, and write the specified character into parentheses. the default character is space.
>>> A = 'hello' >>> B = a. lstrip () >>> print (B) hello # spaces on the right may not be obvious.
Str. rstrip ():Deletes the specified character on the right of the string. the default value is space.
>>> a=' hello '>>> b=a.rstrip()>>> print(b) hello
2. copy the string
>>> a='hello world'>>> b=a>>> print(a,b)hello world hello world
3. connection string
+: Connect two strings >>> a = 'hello' >>>> B = 'world' >>> print (a + B) hello world note: this method is also called "The plus sign of all evil", because the static function string_concat (register PyStringObject * a, register PyObject * B) is called when two strings are connected using the plus sign ), in this function, we will open up a storage unit that is the sum of a + B memory, and then copy the and B strings. If n strings are connected, memory will be opened up for N-1 times, which is very resource-consuming. Str. join: connects two strings. you can specify the join symbol (for join, you can view related information on your own) >>> a = 'hello' >>> B = '####' >>>. join (B) '# hello #'
4. search for strings
# The str. index and str. find functions are the same. The difference is that if the find () search fails,-1 is returned and the program running is not affected. Find is generally used! =-1 or find>-1 as the judgment condition. Str. index: Check whether the string contains a substring 'str'. the value range is a = 'Hello world' >>>. index ('L') 2>. index ('x') Traceback (most recent call last): File"
", Line 1, in
A. index ('x') ValueError: substring not foundstr. find: Check whether the string contains the substring 'str'. you can specify the range >>> a = 'Hello world' >>>. find ('L') 2 >>>. find ('x')-1
5. compare strings
Str. cmp: compares two objects and returns an integer based on the result. X <Y, the return value is negative, and X> Y returns a positive number.
# This method is not available in python3. this is written in the official documentation:
The cmp () function shocould be treated as gone, and the _ cmp _ () special method is no longer supported. use _ lt _ () for sorting, _ eq _ () with _ hash _ (), and other rich comparisons as needed. (If you really need the cmp () functionality, you cocould use the expression (a> B)-(a <B) as the equivalent for cmp (a, B ).)
The general idea is that the cmp () function has "left". if you really need the cmp () function, you can use the expression (a> B)-(a <B) replace cmp (a, B)
>>> a=100>>> b=80>>> cmp(a,b)1
6. whether to include the specified string
in |not in >>> a='hello world'>>> 'hello' in aTrue>>> '123' not in aTrue
7. string length
str.len>>> a='hello world'>>> print(len(a))11
8. convert uppercase and lowercase letters in a string
S. lower () # Convert to lowercase >>> a = 'Hello world' >>> print (. lower () hello worldS. upper () # Convert to uppercase >>> a = 'Hello world' >>> print (. upper () hello worlds. swapcase () # case-insensitive swaps >>> a = 'Hello world' >>> print (. swapcase () hELLO wORLDS. capitalize () # uppercase letter >>> a = 'Hello world' >>> print (. capitalize () Hello world
9. you can specify the length and the two sides of the string in the center position.
str.center()>>> a='hello world'>>> print(a.center(40,'*'))**************hello world***************
10. string statistics
>>> a='hello world'>>> print(a.count('l'))3
11. test and Judge functions of strings. these functions are not in the string Module. these functions 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 () # whether the letters in S are all lowercase S. isupper () # whether the letters in S are uppercase S. istitle () # whether S is capitalized
12. string slicing
Str = '000000' print str [0: 3] # print str [:] # capture all characters of a string from the first to the third. print str [:] # print str [: -3] # print str [2] # capture the third character print str [-1] # capture the first character print str [:: -1] # Create a print str [-3:-1] string that is in the opposite order of the original string # capture the print str [-3:] character before the last and last digits # intercept the last third digit to the end of print str [:-5:-3] # intercept the last fifth digit and the last third digit in reverse order
It should be emphasized that 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.
The above is all the content of this article. I hope it will help you learn python programming.
For more articles about common operations on python strings, refer to PHP Chinese network!