05字符串的常用基本操作

•1,upper()把字符串更改为大写字母,忽略大小写时使用
•2,strip()默认去掉字符串左右两端的空白( space)
•3,replace () 字符串替换
•4,split ()字符串切割
•5,isdigit()判断转这个字符串是否由数字组成
•6, count () 计数器
•7, index()和find() 查找字符串在字符串中出现的位置 index会报错find不会
•8 ,len()它是一个内置函数,和其他函数调用方法不一样 计算字符串,字典,列表等中的长度
•9,startswith ()判断字符串是否以XXX开头 endswith(以XXX结尾)
•10 join() 可以把列表拼接成一个字符串

# 1,upper()把字符串更改为大写字母,忽略大小写时使用
yzm = "GEpengCheng"
a = input ("请输入验证码GEpengCheng:")

if yzm.upper() == a.upper():
    print ("验证正确")
else:
    print ("验证错误")

请输入验证码GEpengCheng:gepengcheng
验证正确

# 2,strip()默认去掉字符串左右两端的空白(
 	 space)
name = "               我 的 名 字 叫 gpc                          "
print(name)
n = name.strip()
print (n)
           我 的 名 字 叫 gpc                          

我 的 名 字 叫 gpc

# 3,replace ( ) 字符串替换
test = "我 、喜 、欢 打  游戏"
print(test)
test1=test.replace("游戏","看书")
print (test1)
test2 = test.replace(" ","")  #去掉所有空格
print (test2)
test2 = test.replace("、","
") 
print (test2)

我 、喜 、欢 打 游戏
我 、喜 、欢 打 看书
我、喜、欢打游戏


欢 打 游戏

# 4,split ()字符串切割
b = ("好_好_学_习,天_天_向_上")
print (b)
b1 = b.split("_") # 切割后就变成了列表
print (b1)

好_好_学_习,天_天_向_上
[‘好’, ‘好’, ‘学’, ‘习,天’, ‘天’, ‘向’, ‘上’]

# 5,isdigit()判断转这个字符串是否由数字组成
money = input (">>>")
if money.isdigit():
    money = int (money)
    print (money)
else:
    money = 0
    print (money*0)

asdsd
0

#6, count () 计数器

s = "小明和小红和小黑,小白,小黄是朋友"
print(s.count("小"))

5

# 7, index()和find() 查找字符串在字符串中出现的位置 index会报错find不会
s = "gpc喜欢雨雨"
print (s.find("喜"))
print(s.index("gpc"))

3
0

# 8 ,len()它是一个内置函数,和其他函数调用方法不一样 计算字符串,字典,列表等中的长度
s = "hahaha"
print (len(s))

6

s = "gpc喜欢雨雨"
i = 0
while i < len(s):
    print (s[i])
    i = i+1

g
p
c



content = input ("请输入内容:")
for a in content:
    if a.isdigit():
        print (a)

请输入内容:asda1212
1
2
1
2

# 9,startswith ()判断字符串是否以XXX开头  endswith(以XXX结尾)
name = input (">>>")
if name.startswith("葛"):
    print ("你姓葛")
else:
    ("你不姓葛")

葛鹏程
你姓葛

name = input (">>>")
if name.endswith("程"):
    print ("yes")
else:
    ("no")

葛鹏程
yes

# 10 join() 可以把列表拼接成一个字符串
lst = ("葛_鹏_程")
print (lst)
s = lst.split("_")
print (s)

print ("_"*30)
l = ['葛', '鹏', '程']
print (l)
ll = "_".join(l)
print (ll)

葛_鹏_程
[‘葛’, ‘鹏’, ‘程’]


[‘葛’, ‘鹏’, ‘程’]
葛_鹏_程

原文地址:https://www.cnblogs.com/gemoumou/p/13635360.html