string

%运算符属于旧的选项

name = 'Michael'
output = 'Hello %s' % name
name = 'Alice'
age = 25
print('My name is {} and I am {} years old.'.format(name, age))
'鼠标位置{0:3d},{1:3d} '.format(x, y)

f-string

从 Python 3.6 开始,Python f 字符串可用。 该字符串具有f前缀,并使用{}评估变量。

name = 'Michael'
output = f'Hello {name}'
num1 = 123.456
num2 = 789.123
print(f"num1 is {num1:.2f}, and num2 is {num2:.3f}")

try:
    a = float("3.15a")
    print(a)
except Exception as ex:
    print(f"Unexpected {ex=}, {type(ex)=}")

r-string 原始字符串

path = r'C:\Michael.log'

Unicode 字符串

u’Hello World !’

bytes 字符串

b” 表示法用于在 Python 中指定 bytes 字符串。与具有 ASCII 字符的常规字符串相比,bytes 字符串是一个字节变量数组,其中每个十六进制元素的值介于 0 和 255。string 变量不是一个普通的字符串;相反,它是一个 bytes 字符串。

string = b"This is a string"
print(string)

str1 = "Hello world"
bytes = str1.encode('utf-8')
str2 = bytes.decode('utf-8')
print(bytes)
print(str2)

Python 字符串格式化

print "My name is %s and weight is %d kg!" % ('Zara', 21) 

repo

函数str() 用于将值转化为适于人阅读的形式, repr() 函数将对象转化为供解释器读取的形式

>>> s = "Michael"
>>> s
'Michael'
>>> repr(s)
"'Michael'"
>>>