9個拼接字符串的方法
1.{} format拼接
通過{}{}{}依次拼接,注意format(必須是Dict或者Tuple類型,不能是字符串或者其它)
print("line {} is OK".format(line));
2.{name} format指定名稱拼接
應用於多項內容拼接,以名稱區分內容
"Line Num= {line_num},Hit time is correct...\n".format(line_num=i)
3.通過 + 拼接
應用於簡單字符串拼接,效率低下,Coding不美觀
"result/"+file_result_sql
4.通過“,”拼接
print('result:' + 'name', 'age' + '\n')
5.隨意拼接
print('result:''name''age' + '\n')
6.join拼接
join把字符數組的內容拼接在一起
str_list = ['name', 'age']
print('result:' + ''.join(str_list) + '\n')
7.通過%拼接
print('%s %s' % ('hello', 'world'))
8.f-string拼接
Python 3.6 中引入了 Formatted String Literals(字面量格式化字符串),简称 f-string,f-string 是 % 操作符和 format 方法的进化版,使用 f-string 连接字符串的方法和使用 %操作符、format 方法类似。
a="hello"
b="world"
print(f'{a} {b}')
a,b="hello","world"
print(f'{a} {b}')
9.通過*拼接
name = " FreeIt "
print(name*3)
文字加顏色
CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "line {} is MISS".format("100"));
轉換成字符串str() 和 repr()
"line_total_num="+str(line_total_num)
去除空格
strip():删除字符串前后(左右两侧)的空格或特殊字符。
lstrip():删除字符串前面(左边)的空格或特殊字符。
rstrip():删除字符串后面(右边)的空格或特殊字符。
str = " abc "
print(str.strip())
print(str.lstrip())
print(str.rstrip())
字符格式化1
%s 字符串 (采用str()的显示)
%r 字符串 (采用repr()的显示)
%c 单个字符
%b 二进制整数
%d 十进制整数
%i 十进制整数
%o 八进制整数
%x 十六进制整数
%e 指数 (基底写为e)
%E 指数 (基底写为E)
%f 浮点数
%F 浮点数,与上相同
%g 指数(e)或浮点数 (根据显示长度)
%G 指数(E)或浮点数 (根据显示长度)
%% 字符"%",显示百分号%
轉義符2
(在行尾时) 续行符
\ 反斜杠符号
’ 单引号
" 双引号
\a 响铃
\b 退格(Backspace)
\e 转义 \000 空
\n 换行
\v 纵向制表符
\t 横向制表符
\r 回车
\f 换页
\oyy 八进制数,y 代表 0~7 的字符,例如:\012代表换行。
\xyy 十六进制数,以 \x 开头,yy代表的字符,例如:\x0a代表换行
\other 其它的字符以普通格式输出
Python String format() Method3
Definition and Usage
The format() method formats the specified value(s) and insert them inside the string’s placeholder.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below.
The format() method returns the formatted string.