go to the spaces at both ends of the string
Task:
Gets a string that has no extra spaces at the beginning and end.
Solution:
The Lstrip, Rstrip, and strip methods of string objects are designed for this task. None of these methods require parameters, and they directly return a copy of the original string that deleted the opening, end, or both ends of the space.
Reference code:
' test 'print'| ', Test_string.lstrip (),'| ', Test_string.rstrip (),'| ', Test_string.strip (),'| '| Test | Test | Test |
Summary:
Each of the three function methods can pass in a parameter that specifies the first and last characters to be removed.
Note that the passed parameter is an array of characters, and the compiler strips out all the corresponding characters at both ends until there are no matching characters, such as:
The argument is "say", then the characters in [' s ', ' a ', ' Y '] array are removed until the character is within the array.
Merging Strings
Task:
There are small strings that combine these small strings into a large string.
Solution:
You can use the string operator join.
The code is as follows:
>>> A ='Qwer'>>> B ='+'. Join (a)>>>b'Q+w+e+r'>>> c="'. Join (a)>>>C'Qwer'>>> d =' '. Join (a)>>>D'Q W e r'
If you want to stitch together strings stored in some variables, use the string formatting operator%
Example: largestring = '%s%s something%s yet more '% (SMALL1,SMALL2,SMALL3)
to reverse a string character by word
Task:
Reverse the string literal character or word by phrase.
Solution:
The string cannot be changed, so reversing a string requires creating a copy. The simplest approach is to use a Teva slicing method with a "step" of-1, which immediately results in a completely inverted effect:
Revchars = Astring[::-1]
If you want to reverse the string by word, we need to create a list of words, reverse the list, and then merge it with the Join method and insert a space between the neighbors:
Example code:
" I am a pythoner ">>> b = a.split ()>>> b.reverse ()". Join (b)>> > b'pythoneraami'. Join (b)>> > b'P y t h o n e r a m I'
< chasing progress, behind 4 sections of content >
Python COOKBOOK2 Chapter I text-go to the spaces at both ends of a string && merge strings && string characters or word-by-phrase