table of Contents
- How to detect whether or not a character string can be transformed into
- How to reverse a string
- Integer and floating point format
- As well as an escape character string format
usage 10.print function
06. How to detect whether or not a character string can be transformed into
s1 = '12345'
print(s1.isdigit())
s2 = '12345e'
print(s2.isalnum())
to sum up
07. How to reverse a string
s1 = 'abcde'
s2 = ''
for c in s1:
s2 = c + s2
print(s2)
edcba
s2 = s1[::-1]
to sum up
08. integer and floating point format
#格式化整数
n = 1234
print(format(n, '10d'))
1234
print(format(n, '0>10d'))
0000001234
print(format(n, '0<10d'))
1234000000
#格式化浮点数
x1 = 123.456
x2 = 30.1
print(format(x1, '0.2f')) #保留小数点后两位
123.46
print(format(x2, '0.2f'))
30.10
#描述format函数
print(format(x2, '*>15.4f')) #右对齐,********30.1000
print(format(x2, '*<15.4f')) #左对齐,30.1000********
print(format(x2, '*^15.4f')) #中间对齐,****30.1000****
print(format(123456789, ',')) #用千位号分隔,123,456,789
print(format(1234567.1235648, ',.2f')) # 1,234,567.12
#科学计数法输出(e大小写都可以)
print(format(x1, 'e')) # 1.234560e+02
print(format(x1, '0.2e')) # 1.23e+02
to sum up
09. character and string escape format
#同时输出单引号和双引号
print('hello "world"') # hello "world"
print("hello 'world'") # hello 'world'
print('"hello" \'world\'') # "hello" 'world'
#让转义符失效(3种方法:r、repr和\)
print(r'Let \'s go!') # Let \'s go!
print(repr('hello\nworld')) # 'hello\nworld'
print('hello\\nworld') # hello\nworld
#保持原始格式输出字符串
print('''
hello
world
''') #三个双引号也可以
to sum up
10.print usage function
#print函数默认空格分隔,并且换行
#用逗号分隔输出的字符串
print('aa', 'bb', sep=',') # aa,bb
print('aa', 'bb', sep='中国') # aa中国bb
#不换行
print('hello', end=' ')
print('world') # hello world
#格式化
s = 's'
print('This is %d word %s' % (10, s))
# 占位符有点过时了,推荐使用format
to sum up