String processing
1. Remove the leading and trailing spaces. strup()
- Strip() is used to remove first and last characters, as well as whitespace (including n, r, t, '', i.e.: line feed, carriage return, tab, space)
st = ' hello python '
print(st)
print(st.strip())
output results :
hello python
hello python
2. Remove the header space. lstrip()
- Lstrip() is used to remove opening characters and whitespace (including n, r, t, '', i.e.: line feed, carriage return, tab, space)
st = ' hello python '
print(st)
print(st.lstrip())
output results :
hello python
hello python
3. Remove trailing spaces. rstrip()
- Rstrip() removes the specified character at the end of the string string and defaults to a blank space, including spaces, line breaks, carriage returns, and tabs.
st = ' hello python '
print(st)
print(st.rstrip())
output results :
hello python
hello python
4. String replacement. replace()
- The replace() method replaces (old string) with (new string) in a string. If the third parameter is specified, the replacement should not exceed MAX times
st = ' hello python '
print(st)
print(st.replace('python', 'word'))
output results :
hello python
hello word
5. String Slice. split ()
-
Slice the string by specifying a delimiter, and if the parameter num has a specified value, only separate num substrings.
-
Split (including multiple spaces, tab t, newline n, etc.) and return all split strings.
st = ' hello python '
print(st)
print(st.split('python'))
st = ' hello n python '
print(st)
print(st.split())
output results :
hello python
[' hello ', ' ']
['hello', 'python']
6. Connect a new string Join()
- The join() method is used to concatenate elements in a sequence with specified characters to generate a new string
st = ' hello python '
print(st)
tt = st.split()
t2 = ''.join(tt)
t3 = ','.join(tt)
print(t2)
print(t3)
output results :
hello python
hellopython
hello,python
7. Change to lowercase letter. lower()
st = 'HELLO PYTHON'
print(st.lower())
output results :
hello python
8. Change to uppercase letters. upper()
st = 'hello python'
print(st.upper())
output results :
HELLO PYTHON
9. Capitalize all first letters of words. title()
st = 'hello python'
print(st.title())
output results :
Hello Python
9. Swap uppercase and lowercase letters. swap case()
st = 'Hello Python'
print(st.swapcase())
output results :
hELLO pYTHON
10. Capitalize the first letter and all others in lowercase. capitalize()
st = 'hello python'
print(st.capitalize())
output results :
Hello python
11. Line break, move the cursor to the beginning of the next line n
st = 'hellonpython'
print(st)
output results :
hello
python
12. Line break, move the cursor to the beginning of the line (delete previous content) r
st = 'hellorpython'
print(st)
output results :
python
13. Tabs, equivalent to 4 spaces t
st = 'hellotpython'
print(st)
output results :
hello python
14. Backspace character, move the cursor to the previous position b
st = 'hellobpython'
print(st)
output results :
hellpython