Table of contents
string expansion
There are three ways to define strings in the python programming language:
①Single quote definition
Example:
name = '我是字符串'
②Definition of double quotation marks
Example:
name = "我也是字符串"
③Definition of triple quotes (support newline)
Example:
name = """
我是
换行了的
字符串
"""
At this point, I can't help but think of a question, if the string wants to contain both single quotes and double quotes, how to write it? Very simple, there are 3 methods:
① Strings containing single quotes can be defined with double quotes;
example:
name = "我是'一个'字符串"
② Strings containing double quotes can be defined with single quotes;
example:
name = '我也是”一个“字符串'
③ Use the escape character \ to dequote the effect, write inEach double-quote or single-quote that needs to be unwrapped is preceded by
example:
name = "\"chen\""
string concatenation
Plus sign +: "string" + "string"
Note: use the plus sign can only complete the connection between strings.
string formatting
Different types of connections:
placeholder splicing ( multiple variables occupy places, variables should be enclosed in brackets, and filled in according to the order of placeholders )
%: means placeholders,
%s: convert character strings into placeholders
%d : Convert an integer into a placeholder
%f: Convert a floating point number into a placeholder
Grammar: "% placeholder"% variable, the second % is the connection function
a = "小白"
b = 2
c = "a是%s,b是%s" % (a, b)
print(c)
Running result: a is Xiaobai, b is 2
Precision Control of Format Strings
m: Control the width, the width is smaller than the number itself, and it will not take effect
. n: Control the precision of the decimal point, and the decimal will be rounded.
m and .n can be omitted
Example: %5d–>integer with a width of 5
%7.2f–>a floating point number with a width of 7 and two decimal places
%.2f—>unlimited width and a floating point number with two decimal places
num1=11
num2=11.345
print("宽度是5,结果%5d"%num1)
print("宽度是7,精度是2,结果%7.2f"%num2)
print("宽度不限制,精度是2,结果%.2f"%num2)
operation result:
String formatting method 2
Quick format:f"string{variable}string"
Example:
print(f"I am {name}")
Formatting of expressions
Expression definition: a code statement with a definite execution result
Example:
print("1*1的结果:%d"%(1*1))
print("1*1的结果:{1*1}")
print("字符串类型是:%s"%type("字符串"))
operation result: