Disclaimer: This article is purely for sharing study notes and experience, exchanging and discussing learning, not for commercial or other purposes
Table of contents
Basic String Operations
1. Escape characters
symbol | illustrate |
\n (commonly used) | Newline, generally used at the end, strip is also valid for it |
\t (commonly used) | Horizontal tab (can be considered as a spacer) |
\r (commonly used) | carriage return |
\v | vertical tab (will have a masculine symbol) |
\a | ring the bell |
\b | Backspace, move cursor forward, overwrite (delete previous one) |
\f | Turn pages (almost never used, a female symbol will appear) |
\' | Single quotes in escape characters |
\" | Double quotes in escape characters |
\\ | escape slash |
2. Placeholder
%s (commonly used) | string (display using str()) |
%d (commonly used) | decimal integer |
%f (commonly used) | floating point number |
%F | floating point number, same as %f |
%c | single character |
%b | binary integer |
%i | decimal integer |
%o | octal integer |
%x | hexadecimal integer |
%e | exponent, base e |
%E | exponent, base E |
%r | string (display using repr()) |
%g | exponent (e) or float (depending on display length) |
%G | exponent (E) or float (depending on display length) |
%% | The character "%", display the percent sign % |
string formatting
1. Use the % symbol to format
Use placeholders to format the output string, here are the three most commonly used usages (%s,%d,%f)
print('他叫%s,今年%d岁了,这次考试考了%f分'%('小明',18,95.5))
#他叫小明,今年18岁了,这次考试考了95.500000分
We found that the printed fraction value reaches 6 decimal places. If you only want to get the first two decimal places and have further requirements for the output format (width or decimal places), you only need to change %f to: %.2f ; The relevant format instructions are as follows:
Syntax: %width.decimal places
%5f-----5 character width floating point number
%5.2f-----5 character width and floating point number with 2 decimal places
%.2-----2 decimal places floating point number
%10s-----Display with a width of 10 characters, if it is insufficient, fill the space on the left (right alignment)
%-10s-----Display with a width of 10 characters, if it is insufficient, fill the space on the right (left alignment)
print('他叫%s,今年%d岁了,这次考试考了%.2f分'%('小明',18,95.5))
#他叫小明,今年18岁了,这次考试考了95.50分
2. Format with f-string
The new functions developed above python3.6 are optimized on the basis of format formatting, which is simpler and easier to understand, and runs faster
Single line: Syntax: Add f before the statement, enclose the part that needs to be filled in braces {}, fill in the variables or values that need to be filled in the braces, etc.
name='小明'
age=18
print(f'他叫{name},今年{age}岁了')
#他叫小明,今年18岁了
Multiple lines: f must be added in front of each line, otherwise the second example below will appear
name='小明'
age=18
print(
f'他叫{name}'
f'今年{age}岁了')
#他叫小明今年18岁了
name='小明'
age=18
print(
f'他叫{name}'
'今年{age}岁了')
#他叫小明今年{age}岁了
3. Use format to format
Compared with the previous two formats, format is more cumbersome, so it is generally not recommended to use
Syntax: <template string>.format(<parameters separated by commas>) The places that need to be filled are enclosed in braces {}, and the end of the statement is formatted with .format()
print('他叫{},今年{}岁了'.format('小明',18))
#他叫小明,今年18岁了
If you have further requirements on the output format, please refer to:
{<parameter number>:<format control token>}
The format control token is as follows:
{:<fill><alignment><width><,><.precision><type>}
a='python'
print("{0:30}".format(a) )#默认左对齐
#python
print("{0:>30}".format(a)) #右对齐
# python
print("{0:*^30}".format(a))#居中且使用*填充
#************python************
print("{0:-^30}".format(a)) #居中且使用-填充
#------------python------------
String Common Methods
method | effect |
find() | In a certain string, find a desired string |
join() | Only used for string concatenation, be careful not to concatenate other values |
lower() | uppercase to lowercase |
upper() | lowercase to uppercase |
swapcase() | reverse case |
replace() | replace string |
split() | Slicing a string by specifying a delimiter |
strip() | Remove leading and trailing spaces or some leading and trailing characters |
translate() | Swap or filter characters |
find() Find method (case sensitive)
Syntax: find('search string', start bit, end bit)
s='Welcome to China'
print(s.find('to'))#可以查找某个单词,返回单词起始处的索引
#8
print(s.find('o'))#也可以查找某个字母,找到第一个出现的字母的索引
#4
print(s.find('a',0,8))#在索引0到8之间查找字母a,如果没有找到,返回-1
#-1
join() string concatenation
Syntax: 'separator'.join(element sequence, string, tuple, dictionary that needs to be spliced)
s=['a','b','c','d']
print('+'.join(s))#通过+号连接字符串
#a+b+c+d
print(''.join(s))#无符号连接字符串
#abcd
lower() uppercase to lowercase
Syntax: str.lower()
s='Welcome to China'
print(s.lower())#将大写全部转为小写
#welcome to china
upper() lowercase to uppercase
Syntax: str.upper()
s='Welcome to China'
print(s.upper())#将小写全部转为大写
#WELCOME TO CHINA
swapcase() reverse case
Syntax: str.swapcase()
s='Welcome to China'
print(s.swapcase())#将大小写互反转
#wELCOME TO cHINA
replace() replaces the string
Syntax: str.replace('original value', 'replaced value', number of replacements)
s='Welcome to China'
print(s.replace('o','W'))#将所有字母o替换成字母W
#WelcWme tW China
print(s.replace('o','W',1))#将字母o替换成字母W,替换一个
#WelcWme to China
split() slices by specifying the delimiter
Syntax: str.split('separator', number of times)
s='Welcome to China'
print(s.split())#通过空格分割
#['Welcome', 'to', 'China']
print(s.split('o'))#通过字母o分割
#['Welc', 'me t', ' China']
strip() 去除首尾空格或首尾字符
语法:str.strip('需要去除的字符')
s='------abcd------'
print(s.strip('-'))#去除首尾-符号
#abcd
a='aabbccddccbbaa'
print(a.strip('a'))#去除首尾的a字母
#bbccddccbb
translate() 对字符进行交换或过滤
语法:str.translate(映射表)
可用于加密,但是安全性不太高,所以不建议使用translate()进行加密
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)#创建映射表
s = "my name is XIAOMING"
print (s.translate(trantab))
#my n1m2 3s XIAOMING