Python 循环、字符串常用方法、条件判断
一、字符串常用方法,以下几个方法必须要记住
# 这几个方法必须得会
# #replace
# strip
# join
# split
# isdight
# upper
# lower
# format
# startswith endswish
# count
# zfill
strip:默认去掉字符串两边的空格和换行符
s='.abc.' new_s=s.strip('.') #默认去掉字符串两边的空格和换行符,括号里的可以改
replace:replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
b = 'hhhhhhhhhhhhhhhhaaaaaaa' print(b.replace('h','ABC',5)) #h是被替换的那个 把h替换为ABC,替换5次
join:以某个字符串把list里边元素连接起来 ;能把list变成字符串
name = ['xiaohei','haha','xiaomi']
new_name = str(name)
# print(name)
# print(new_name[2])
res = '*'.join(name) #对列表进行连接
res1 = '&'.join(new_name) #对字符串进行连接
print(res)
print(res1)
split:按照某个字符来分隔字符串,返回一个list,很重要
# s='user1,user2,user3,ser4,user5,user6,user7' # print(s.split(','))
二、字符串格式化
第二种:占位符 word2 = '欢迎%s登录。。今天的日期是%s'%(username,today) # 写%s说明这位置已经有人占了,后面跟上一个%,%s就相当于username,前面有几个%s,后面就写几个变量 print(word2) %d:只能跟整数,%f只能跟小数 word3 = '你的年龄是 %05d 你的分数是%.2f'%(18,92.3) print(word3)

浙公网安备 33010602011771号