目录
- 如何检测一个字符串是否可以转换为数字
- 如何反转字符串
- 格式化整数和浮点数
- 字符串转义字符以及格式
10.print函数的用法
06.如何检测一个字符串是否可以转换为数字
s1 = '12345'
print(s1.isdigit())
s2 = '12345e'
print(s2.isalnum())
总结
07.如何反转字符串
s1 = 'abcde'
s2 = ''
for c in s1:
s2 = c + s2
print(s2)
edcba
s2 = s1[::-1]
总结
08.格式化整数和浮点数
#格式化整数
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
总结
09.字符串转义字符以及格式
#同时输出单引号和双引号
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
''') #三个双引号也可以
总结
10.print函数的用法
#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
总结