- r syntax
- In Python, you can add r/R to the front of the string (before the quotation marks) to prevent escape characters in the string from escaping
- r can make the escape characters in the string become ordinary characters
str1 = '\tabc\n123'
print(str1)
str2 = r'\tabc\n123'
print(str2) # \tabc\n123
path = R'c:\\prog\name\yuting\xuexi\aa.txt'
print(path)
2. Format string
name = '小明'
age = 18
money = 18
# 完成以下格式的message
# message = 'xxx今年xx岁!月薪xxK!'
# 方法一:字符串拼接
message = name+'今年'+str(age)+'岁!月薪'+str(money)+'K!'
print(message)
Method 2:% format string
1) Syntax: a string containing format placeholders% (data 1, data 2, data 3,...)-The data must correspond to the placeholders one to one
2) Placeholder
%s- String (can be assigned with any data)
%d-integer (only numbers, automatically converted to integers when filling)
%f-floating point numbers (only numbers), the default has 6 decimal places, %.Nf- Keep N decimal places, rounding is used when keeping decimals
message = '%s今年%d岁!月薪%dK!' % (name, age, money)
print(message)
str3 = '%.2f-' % (29.2899)
print(str3)
Method 3: f-String
message = f'{name} {age*10} years old this year! Monthly salary {money}K! '
print(message)
1) Control the number of decimal places
{data:.Nf}-control data to retain N decimal places
num = 1.234
result = f'数字:{num:.2f}'
print(result)
2) Control the length of the data
{data: padding character> length}-convert the data into a character string of the specified length, fill in the left with the specified character if it is not enough
{data: pad character <length}-convert the data into a character string of the specified length , Not enough to fill in the right with the specified characters
num = 23
result = f'学号:{num:x<4}'
print(result)
3) Percentage
{Data:.N%}-Convert decimals to percentages, while the number retains N decimal places
num = 0.2567
result = f'及格率:{num:.2%}'
print(result)
4) Comma separated
(data:,)
num = 18920000000
result = f'余额:{num:,}'
print(result)