在Python中,百分号(%)具有两种主要用途:
取模运算(Modulo Operation)
当用于两个整数之间时,表示求余数。例如,`7 % 3` 的结果是 `1`,因为 `7 = 3 * 2 + 1`。
字符串格式化
用途之一是在字符串中插入变量值。例如,`message = "My name is %s and I am %d years old." % ("Alice", 30)` 会生成字符串 "My name is Alice and I am 30 years old."。
其中 `%s` 表示字符串占位符,`%d` 表示整数占位符,`%f` 表示浮点数占位符等。
还有一些转换字符,如 `%c`(整数转成对应的ASCII字符),`%o`(整数转成八进位),`%x`(整数转成十六进位)等。