当前位置: 移动技术网 > IT编程>脚本编程>Python > (自兴人工智能)python字符串

(自兴人工智能)python字符串

2018年02月21日  | 移动技术网IT编程  | 我要评论

杨恭如浴室,泡泡染发剂好用吗,武汉晨报电子版

字符串是python中最常用的数据类型,我们可以使用单引号(' ')或双引号(" ")来创建字符串。

a='Hello'
b="Hello"

所有标准序列操作如(索引,分片,成员资格,求长度,取最小值和最大值等),对字符串同样适用。

字符串常用的格式化符号:

(%s 格式化字符串)

print('Hello,%s'%'world') #使用%s作为'world'的占位符
Hello,world #结果

print('还有%s天'%10) #使用%d作为10的占位符
还有10天 #结果
#%s不仅可以格式化字符串,还可以格式化整数

(%d 格式化整数)

print('还有%d天'%10) #使用%d作为10的占位符
还有10天 #结果

 字符串常用的方法:

find():用于检测字符串中是否包含子字符串str,可以指定开始和结束的范围。

a='hello,world'
print(a.find('wo'))
6 #返回了匹配值的索引
print(a.find('kb'))
-1 #找不到,返回-1
print(a.find('wo',3)) #提供起点
6 #结果
print(a.find('wd',6))
-1 #结果
print(a.find('wo',3,8)) #提供起点和终点
6 #结果
print(a.find('wd',3,7))
-1 #结果

lower():将字符串中所有大写字符转换为小写

a='HeLlo'
b=a.lower()
print(b)
hello #结果

upper():将字符串中所有小写字符转换为大写

a='HeLlo'
b=a.upper()
print(b)
HELLO #结果

swapcase():将字符串中所有小写字符转换为大写,大写字符转换为小写

a='HeLlo'
b=a.swapcase()
print(b)
hElLO #结果

replace():把字符串中的旧字符串替换成新字符串

a='hello world'
b=a.replace('hello','HELLO')
print(b)
HELLO world #结果

strip():移除字符串头尾指定字符

a='++hello world++'
b=a.strip('+')
print(b)
hello world #结果

b=a.strip('++h')
print(b)
ello world #结果

b=a.strip('++d')
print(b)
hello worl #结果

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网