字符串
1.什么是字符串
- 用引号引起来的一串字符
- 用引号创建字符串。
- 单引号
- 双引号
- 三单引号
- 三双引号
##创建字符串
# 创建字符串
name = "Hang zhou"
area = "GongShu"
history = "5000"
famous_person = """苏轼,许仙,白素贞"""
capticalOf = '''吴越,南宋'''
print(type(name), type(area), type(history), type(famous_person), type(capticalOf))
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
<class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'>
Process finished with exit code 0
##字符串的运算和常见操作
# 字符串的运算和常见操作
# (1)拼接
a = "Hello"
b = ",Python"
print(a + b)
a = ["Hello"]
b = [",Python"]
print(a + b)
# 拼接基于同一种数据类型
#
#(2)重复
#
a = "City College "
print(a*3)
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
Hello,Python
['Hello', ',Python']
City College City College City College
Process finished with exit code 0
# (3)索引(偏移)[],切片[:],[::]
sr = "Python"
i = 0
for i in range(len(sr)):
print(sr[i], end=" ")
print()
for i in sr:
print(i, end=" ")
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
P y t h o n
P y t h o n
Process finished with exit code 0
# 切片
sr = "Life is short ,you need python."
print(len(sr))
print(sr[1::2]) # 前闭后开
print(sr[::-1])
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
31
iei hr yune yhn
.nohtyp deen uoy, trohs si efiL
Process finished with exit code 0
# (4)大小写转换
# sr.lower():转小写
# sr.upper()转大写
# sr.swapcase()大小写互换
# sr.title()转为标题的形式
# sr.capitallize首字母大写
sr = "Life is short ,you need python."
print(sr.lower())
print(sr.upper())
print(sr.swapcase())
print(sr.title())
print(sr.capitalize())
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
life is short ,you need python.
LIFE IS SHORT ,YOU NEED PYTHON.
lIFE IS SHORT ,YOU NEED PYTHON.
Life Is Short ,You Need Python.
Life is short ,you need python.
Process finished with exit code 0
# 验证码确认
keyword = "qwer"
x = input("输入验证码")
if x.lower() == keyword.lower():
print("验证码正确")
else:
print("验证码错误")
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
输入验证码qwer
验证码正确
Process finished with exit code 0
# (5)字符串的格式输出对齐
# sr.center([len],[填充符号]),居中对齐
# sr.ljust([len],[填充符号]),居左对齐
# sr.rjust([len],[填充符号]),居右对齐
# sr.zfill([len]),居右对齐,默认填充0
sr = "Life is short ,you need python."
print(sr.center(41, '#'))
print(sr.ljust(41, "#"))
print(sr.rjust(41, "#"))
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
#####Life is short ,you need python.#####
Life is short ,you need python.##########
##########Life is short ,you need python.
Process finished with exit code 0
# (6)删除指定字符
# sr.strip()
# sr.lstrip()
# sr.rstrip()
sr = "#####Life is short ,you need python.#####"
print(sr.strip("#")) # 不传递参数默认删除\n \t
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
Life is short ,you need python.
Process finished with exit code 0
# (7)计数
# sr.count()
sr = "Life is short ,you need python."
print(sr.count('o', 9, 17))
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
2
Process finished with exit code 0
(8)字符串搜索定位和替换
sr.find()查找元素并返回第一次出现的元素的索引值,查找不到返回-1
sr.index()查找元素并返回第一次出现的元素的索引值,查找不到报错
sr.rindex()从右往左查找
sr.replace([现有],[替换])
sr = "Life is short ,you need python."
print(sr.find('e'))
print(sr.index('e'))
print(sr.rindex('e'))
print(sr.replace('you need', 'I use'))
print(sr.replace('t', 'T', 1))
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
3
3
21
Life is short ,I use python.
Life is shorT ,you need python.
Process finished with exit code 0
# (9)字符串条件判断
# isalnum,判断的字符串有字母或者数字组成
# isalpha()仅有字母
# isdigit()仅有数字
a = "abc666def"
b = "666"
print(b.isalnum())
print(a.isalpha())
print(a.isdigit())
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
True
False
False
Process finished with exit code 0
(10)制表符的转化
sr.expandtabs()
nm = "0123456789012345678901234567890123456789"
sr = "Lif\te is short ,\t you need python."
print(nm)
print(sr.expandtabs(4))
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
0123456789012345678901234567890123456789
Lif e is short , you need python.
Process finished with exit code 0
# (11)字符串的分割变换
# join(),将指定字符插入到元素之间
# splist(),以指定字符分割字符串并去除该字符
# partition(),以指定字符分割字符串并保留该字符
sr = "Life is short ,you need python."
print('+'.join(sr))
li = ["I", "love", "Python"]
print(' '.join(li))
print(sr.split('o'))
print(sr.split('o',2))
print(sr.partition('o'))
/usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py
L+i+f+e+ +i+s+ +s+h+o+r+t+ +,+y+o+u+ +n+e+e+d+ +p+y+t+h+o+n+.
I love Python
['Life is sh', 'rt ,y', 'u need pyth', 'n.']
['Life is sh', 'rt ,y', 'u need python.']
('Life is sh', 'o', 'rt ,you need python.')
Process finished with exit code 0
-
设计“过7游戏”的程序,打印出1-100之间除了含7和7的倍数之外的所有数字。
i = 0 while i <= 100: if i % 7 != 0: print(i, end=" ") i = i + 1 /usr/local/bin/python3.6 /Users/shaojun/PycharmProjects/7.17/2.py 1 2 3 4 5 6 8 9 10 11 12 13 15 16 17 18 19 20 22 23 24 25 26 27 29 30 31 32 33 34 36 37 38 39 40 41 43 44 45 46 47 48 50 51 52 53 54 55 57 58 59 60 61 62 64 65 66 67 68 69 71 72 73 74 75 76 78 79 80 81 82 83 85 86 87 88 89 90 92 93 94 95 96 97 99 100 Process finished with exit code 0
-
编写程序用户登陆且仅有三次机会(if和for)
username = "user1" userpassword = "123456" i = 1 while True: a = str(input("请输入账号\n")) b = str(input("请输入密码\n")) if a == username and b == userpassword: print("登陆成功\n") break else: i = i + 1 if i>3: break print("登陆失败\n")
-
编写程序实现,判断一串字符是否为有效变量名
x = input("输入字符串\n") if x[0].isdigit(): print("无效变量名") else: for i in x: if i.isalpha() or i == "_": print("有效变量名") break else: print("无效变量名")
-
最多猜10次数字的游戏,猜测范围1-100,根据input内容提示猜大或者猜小,如果猜中,结束循环
import random x = random.randint(1, 101) i = 0 j = 1 while x != i and j <= 10: i = int(input("请输入猜测数字:\n")) if x > i: print("第", j, "次", "猜小了\n") if j == 10: print("次数耗尽") j = j + 1 if x < i: print("第", j, "次", "猜大了\n") if j == 10: print("次数耗尽") j = j + 1 if x == i: print("正确")
-
使用while循环实现输出2-3+4-5+6…+100的和
i = 2 j = 1 sum = 0 while i <= 100: x = (-j) ** i sum = sum + i * x i = i + 1 print(sum)
-
使用循环实现九九乘法表
for i in range(1, 10): for j in range(1, 10): if i >= j: print(j, "*", i, "=", i * j, end=" ") print()
-
已知列表li=[22478,24066,23398,38498],利用字符串拼接及遍历,输出结果“城市学院”
li = [22478, 24066, 23398, 38498]
for i in li:
print(chr(i), end=" ")