字符串或串(String)是由数字、字母、下划线组成的一串字符。Python 里面最常见的类型。 可以简单地通过在引号间(单引号,双引号和三引号)包含字符的方式创建它。
常用的转义符号:
example:
name = 'westos'
print('hello ' + name)
# 1元 + 1分 = 1元 + 0.01元 = 1.01元
print('hello' + str(1))
print("*" * 30 + '学生管理系统' + '*' * 30)
example:
data = pd.read_csv(
'https://labfile.oss.aliyuncs.com/courses/1283/adult.data.csv')
print(data.head())
example:
s = 'WESTOS'
print(s[0]) # 'W'
print(s[3]) # 'T'
print(s[-3]) # 'T'
example:
s = 'hello westos'
print(s[1:3]) # 'el'
print(s[:3]) # 'hel'
print(s[:5]) # 拿出字符串的前5个字符
print(s[1:]) # 'ello westos'
print(s[2:]) # 'llo westos'
print(s[:]) # 拷贝字符串
print(s[::-1]) # 倒序输出
example:
s = 'westos'
count = 0
for item in s:
count += 1
print(f"第{count}个字符:{item}")
1. 类型判断
s = 'HelloWESTOS'
print(s.isalnum()) %判断是否是字母或数字
print(s.isdigit()) %判断是否是数字
print(s.isupper()) %判断是否为大写
2. 类型的转换
print('hello'.upper()) %均转换为大写
print('HellO'.lower()) %均转换为小写
print('HellO WOrld'.title()) %首字母大写
print('HellO WOrld'.capitalize()) %capitalize()将字符串的第一个字母变成大写,其他字母变小写
print('HellO WOrld'.swapcase()) %swapcase() 方法用于对字符串的大小写字母进行转换
lstrip: 删除字符串左边的空格(指广义的空格: \n, \t, ' ')
rstrip: 删除字符串右边的空格(指广义的空格: \n, \t, ' ')
strip: 删除字符串左边和右边的空格(指广义的空格: \n, \t, ' ')
replace: 替换函数, 删除中间的空格, 将空格替换为空。replace(" ", )
a = " hello ".strip()
print(a)
b = " hello ".lstrip()
print(b)
c = " hello ".rstrip()
print(c)
d = " hel lo ".replace(" ", "")
print(d)
print("学生管理系统".center(50))
print("学生管理系统".center(50, "*"))
print("学生管理系统".center(50, "-"))
print("学生管理系统".ljust(50, "-"))
print("学生管理系统".rjust(50, "-"))
s = "hello westos"
print(s.find("llo"))
print(s.index("llo"))
print(s.find("xxx"))
print(s.count("xxx"))
print(s.count("l"))
print(s.count("o"))
#print(s.index("xxx")) %index如果找到子串,则返回子串开始的索引位置。否则报错(抛出异常).
ip = "172.25.254.100"
print(ip.split('.'))
items = ip.split('.')
print(items)
print("-".join(items))
import random
import string
print(random.choice("0123456789"))
print(random.choice("0123456789") + random.choice('0123456789'))
print(string.ascii_letters)
print(random.sample(string.ascii_letters, 4))
print("".join(random.sample(string.ascii_letters, 4)))
print( "".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4)))
for i in range(100): %循环输出100个由两个数字和四个字母随机组合的验证码
print("".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4)))
import random
count = 10
right_count = 0
for i in range(count):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
symbol = random.choice(["+", "-", "*"])
result = eval(f"{num1}{symbol}{num2}")
question = f"{num1} {symbol} {num2} = ?"
print(question)
user_answer = int(input("Answer:"))
if user_answer == result:
print("Right")
right_count += 1
else:
print("Error")
print("Right percent: %.2f%%" %(right_count/count*100))
s = input('输入字符串:')
result = "回文字符串" if s == s[::-1] else "不是回文字符串"
print(s + "是" + result)
或者:
s = input("请输入字符串:")
if s[:] == s[::-1]:
print(f"{s}是回文字符")
else:
print(f"{s}不是回文字符")