Python-字符串格式

时间:2020-02-23 14:43:26  来源:igfitidea点击:

在本教程中,我们将学习Python中的字符串格式。

我们使用 %Python中用于格式化字符串的符号。

下面是我们可以使用的符号列表 %在Python中设置字符串格式的符号。

说明转义序列表示法
%c字符
%s字符串
%i整数
%d有符号整数
%i无符号整数
%o八进制整数
%x十六进制小写
%X十六进制大写
%e带小写'e'的指数表示法。
%E带大写'E'的指数表示法。
%f浮点数
%g是%f和%e的缩写
%G是%F和%E的缩写

字符串格式示例

在下面的Python练习中,我们使用 %c操作符。

练习1:插入字符

在这个Python程序中,我们使用 %s.

# character
ch = 'A'
# string format
str = "We are inserting the following character: %c" % (ch)
# output
print(str)

我们将得到以下输出。 %i保存在变量中的字符 %d插入位置 %i在字符串中 %o.

练习2:插入字符串

在这个Python程序中,我们使用 %x.

# string to insert
str_insert = 'World'
# string format
str = "Hello %s" % (str_insert)
# output
print(str)

我们将得到以下输出。 %X字符串"World"保存在变量中 %e插入位置 e在字符串中 %E.

练习3:插入整数

在这个Python程序中,我们使用 E.

# integer
i = 10
# string format
str = "We have the following integer value %i" % (i)
# output
print(str)

我们将得到以下输出。 %f

练习4:插入浮点数

在这个Python程序中,我们使用 %g.

# floating point number
f = 123.45
# string format
str = "We have the following floating point value %f" % (f)
# output
print(str)

我们将得到以下输出。 %G

练习5:插入八进制值

在这个Python程序中,我们插入整数值,它用 %.

# integer
i = 12
# string format
str = "We have the following octal value %o for integer %i" % (i, i)
# output
print(str)

我们将得到以下输出。 %c

练习6:插入十六进制值

在这个Python程序中,我们插入整数值,它用 We are inserting the following character: A(小写)和 ch(大写)。

# integer
i = 27
# string format
str1 = "We have the following lowercase hexadecimal value %x for integer %i" % (i, i)
str2 = "We have the following uppercase hexadecimal value %X for integer %i" % (i, i)
# output
print(str1)
print(str2)

我们将得到以下输出。

We have the following lowercase hexadecimal value 1b for integer 27
We have the following uppercase hexadecimal value 1B for integer 27