Python面试一百题——核心基础(2)

目录

  1. 如何检测一个字符串是否可以转换为数字
  2. 如何反转字符串
  3. 格式化整数和浮点数
  4. 字符串转义字符以及格式
    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函数默认空格分隔,并且换行
#用逗号分隔输出的字符串
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

总结
在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值