系列文章:
04 如何检测一个字符串是否可以转换为数字
Q1:如何检测字符串是否为数字(数字和字母混合形式)
是否为数字:isdigit()
是否为数字字母混合:isalnum()
# 1 检测字符串是否为数字
s1 = '12345'
print(s1,s1.isdigit()) # 检测整数
s2 = '12345a'
print(s2,s2.isalnum()) # 是否为数字字母混合形式
s3 = '12_345a'
print(s3,s3.isalnum())
print("12.34".isdecimal()) # 检测是否为整数:是,True
print('abcd'.isalpha())
后台回复 Python字符串,获取更详细整理链接。
Q2 :怎样将一个字符串转换为数字才安全
先使用 isdigit() 判断是否为数字,是,则转换;不是,另作处理。
# 转换前先判断
s2 = '123a'
if s2.isdigit():
print(int(s2))
else:
print('不是纯数字')
try:
print(int('223a'))
except Exception as e:
print('该数不是纯数字,不可转换')
print(e)
05 如何反转字符串
Q1:如何反转一个字符串
使用循环,拼接
s1 = 'abcde'
s2 = ''
for c in s1:
s2 = c + s2
print(s2)
Q2:如何用分片反转字符串
将步长设置为 -1 ,也就是[::-1]
#[a:b:c]
print(s1[::-1])
06 格式化整数和浮点数 Q1:请格式化一个整数,按 10 位输出,不足 10 位前面补 0
format 函数
# 1 格式化整数
n = 1234
print(format(n,'10d')) # 默认补空格, 1234
print(format(n,'0>10d')) # 左侧补 0,0000001234
print(format(n,'0<10d')) # 右侧补 0,1234000000
Q2:格式化一个浮点数,要保留小数点有 2 位
# 2 格式化浮点数
x1 = 123.34893
x2 = 13.2
print(format(x1,'0.2f')) # 保留小数点后两位,123.35
Q3:请描述 format 函数的主要用法
1.03乘10的8次方,可简写为“1.03E+08”的形式
format 函数,第一个参数为 待格式化参数,第二个参数为 指定格式
# 3 描述 format 函数
print(format(x2,'*>13.4f')) # 右对齐,13位,保留4位小数。小数点是占一位的
# ******13.2000
print(format(x2,'*<13.4f')) # 左对齐,右边补 * 号
# 13.2000******
print(format(x2,'*^13.4f')) # 中心对齐
# ***13.2000***
print(format(123456789,',')) # 千位号分割
# 123,456,789
print(format(1234567.34987,',.2f')) # 整数千位号分割,小数保留两位
# 1,234,567.35
print(format(x1,'e')) # 科学计数法
# 1.233489e+02
print(format(x1,'0.2e')) # 科学计数法的混合,保留两位小数
# 1.23e+02
07走进字符串的世界 Q1:如何同时在字符串中显示单引号和双引号
转义符的使用
# 1 同时输出单引号和双引号
# 字符串的引号和表示想保留输出的字符的引号一样,需加转义字符
print('"hello" \'world\'')
3种:r、repr 和 \
# 2 让转义符失效( 3 种方法:r、repr 和 \ )
print('Let\'s go!')
print(r'Let\'s go!') # r
print('hello\nworld')
print(repr('hello\nworld')) # repr 单引号也输出
print('hello\\nworld') # \
三对单引号 或者 三对双引号
# 3 保持原始格式输出字符串 三对单引号或者三对双引号
print('''hello
world
i love you''')
08print 函数探讨
使用 sep 参数设置字符串之间的分隔符,默认是空格
# 用一个字符串作为输出字符串的分隔符
print('aa','bb',sep=",")
使用 end 参数设置结尾符号,默认是换行符
# 2 如何让print不换行 end=" "
print('hello',end=' ')
print('world')
使用 % 格式化字符串
并且重定向到一个变量
# 3格式化print
s = 'road'
x = len(s)
# print('The length of %s is %d' % (s,x))
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print('The length of %s is %d' % (s,x))
sys.stdout = old_stdout
result_str = result.getvalue()
print('result_str',result_str,sep=':')