python中字符串的使用

本文详细介绍了Python中的字符串定义、特性,包括索引、切片、重复、连接等操作。同时,讨论了字符串在回文数判断、大小写和数字判断、开头结尾匹配、去除空格、搜索与替换等方面的应用。此外,还提供了出勤纪录判断、句子反转、字符串删除和加法练习等实际问题的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、字符串定义方式

a = 'hello'
b = 'what\'s up'
c = "what's up"
print(a)
print(b)
print(c)

二、字符串的特性

1.索引

s = 'hello'
print(s[0])
print(s[1])

2.切片
切片的规则:s[start?step] 从start开始到end-1结束,步长:step

print(s[0:3])
print(s[0:4:2])

#显示所有字符

print(s[:])

#显示前3个字符

print(s[:3])

#对字符串倒叙输出

print(s[::-1])

#除了第一个字符以外,其他全部显示

print(s[1:])

3.重复

print(s * 5)

4.连接

print(s + 'world')

5.成员操作符

print('h' in s)

6.for循环(迭代)

for i in s:
    print(i)

三、回文数判断
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因>此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。

“”"

num = input('Num:')
if num == num[::-1]:
    print('这是一个回文数')
else:
    print('这不是一个回文数')

四、字符串判断大小写和数字
#判断字符串里每个元素是否为 什么类型
#一旦有一个元素不满足,就返回False

print('123'.isdigit())
print('123abc'.isdigit())

#title:标题 判断某个字符串是否为标题(第一个字母大写,其余字母小写)

print('Hello'.istitle())
print('HeLlo'.istitle())

#upper:大写字母 判断某个字符串是否全为大写

print('hello'.upper())
print('hello'.isupper())

#lower:小写字母 判断某个字符串是否全为小写

print('HELLO'.lower())
print('HELLO'.islower())

#alnum:字母数字 判断某个字符串是否是字母+数字的形式

print('hello123'.isalnum())

#alpha:字母 判断某个字符串是否为字母

print('123'.isalpha())
print('aaa'.isalpha())

五、字符串开头结尾的匹配

filename = 'hello.loggg'
if filename.endswith('.log'):
   print(filename)
else:
   print('error filename')

url1 = 'file:///mnt'
url2 = 'ftp://172.25.254.250/pub'
url3 = 'https://172.25.254.250/index.html'

if url3.startswith('http://'):
    print('获取网页')
else:
    print('未找到网页')

六、字符串去除两边空格

s = '      hello      '
s.strip()
输出:'hello'
s.rstrip()
输出:'      hello'
s.lstrip()
输出:'hello      '
s = '\nhelloh\t\t'
输出:s = 'helloh'
s.strip('h')
输出:'ello'
s.rstrip('h')
输出:'hello'
s.lstrip('he') 
输出:'lloh'

七、字符串练习
变量名是否合法:
1.变量名可以由字母,数字或者下划线组成
2.变量名只能以字母或者下划线开头
s = ‘hello@’

1.判断变量名的第一个元素是否为字母或者下划线 s[0]
2.如果第一个元素符合条件,判断除了第一个元素之外的其他元素s[1:]

“”"
#1.变量名的第一个字符是否为字母或下划线
#2.如果是,继续判断 --> 4
#3.如果不是,报错
#4.依次判断除了第一个字符之外的其他字符
#5.判断是否为字母数字或者下划线

while True:
    s = input('变量名:')
    if s == 'exit':
        print('欢迎下次使用')
        break
    if s[0].isalpha() or s[0] == '_':
        for i in s[1:]:
            if not(i.isalnum() or i == '_'):
                print('%s变量名不合法' %s)
                break
        else:
            print('%s变量名合法' %s)
    else:
        print('%s变量名不合法' %s)

八、字符串的搜索与替换

s = 'hello world hello'

#find找到子串,并返回最小的索引

print(s.find('hello'))
print(s.find('world'))

#rfind找到子串,并返回最大索引

print(s.rfind('hello'))

#替换字符串中所有的’hello’为’westos’

print(s.replace('hello','westos'))

九、练习九九乘法表

i = 1
while i < 10:
    j = 1
    while j <= i:
        print('%d*%d=%d\t' %(j, i, i*j) , end=(''))
        j +=1
    print('')
    i +=1
print('')

# i = 9
# while i > 0:
#     j = 1
#     while j <= i:
#         print('%d*%d=%d\t' %(j,i,j*i), end=(''))
#         j +=1
#     print('')
#     i -=1
# print('')

# i = 1
# while i <= 9:
#     k = 8
#     j = 1
#     while k >= i:
#         print('\t\t', end=(''))
#         k -= 1
#     while j <= i:
#         print('%d*%d=%d\t' % (j, i, i * j), end=(''))
#         j += 1
#     print('')
#     i += 1
# print('')

i = 9
while i > 0:
    j = 1
    k = 8
    while k >= i:
        print('\t\t', end=(''))
        k -= 1
    while j <= i:
        print('%d*%d=%d\t' % (j, i, j * i), end=(''))
        j += 1
    print('')
    i -= 1
print('')

十、字符串的对齐
print(‘学生管理系统’.center(30))
print(‘学生管理系统’.center(30,’’))
print(‘学生管理系统’.ljust(30,’
’))
print(‘学生管理系统’.rjust(30,’*’))
print(‘学生管理系统’.rjust(30,’@’))

十一、字符串的统计
count:统计个数
len统计长度

print('hello'.count('l'))
print('hello'.count('ll'))
print(len('hello'))

十二、字符串的分离和连接

s = '172.25.254.250'
s1 = s.split('.')
print(s1)
print(s1[::-1])

date = '2019-01-15'
date1 = date.split('-')
print(date1)

#通过指定的字符进行连接

print(''.join(date1))
print('/'.join(date1))

十三、字符串练习
“”"
给定一个字符串来代表一个学生的出勤纪录,这个纪录仅包含以下三个
字符:
‘A’ : Absent,缺勤
‘L’ : Late,迟到
‘P’ : Present,到场
如果一个学生的出勤纪录中不超过一个’A’(缺勤)并且不超过两个连续的’L’(迟到),
那么这个学生会被奖赏。
你需要根据这个学生的出勤纪录判断他是否会被奖赏。
示例 1:
输入: “PPALLP”
输出: True
示例 2:
输入: “PPALLL”
输出: False

“”"

import random
print(random.randint(1,40))

s = input(‘输入考勤记录:’)

# if s.count(‘A’) <= 1 and s.count(‘LLL’) == 0:

# print(‘True’)

# else:

# print(‘False’)

print(s.count(‘A’) <= 1 and s.count(‘LLL’) == 0)

十四、小米笔试题
(2017-小米-句子反转)

  • 题目描述:

给定一个句子(只包含字母和空格), 将句子中的单词位置反转,>单词用空格分割, 单词之间只有一个空格,前>后没有空格。
比如: (1) “hello xiao mi”-> “mi xiao hello”

  • 输入描述:

输入数据有多组,每组占一行,包含一个句子(句子长度小于1000个>字符)

  • 输出描述:

对于每个测试示例,要求输出句子中单词反转后形成的句子

  • 示例1:

  • 输入
    hello xiao mi

  • 输出
    mi xiao hello

    print(’ '.join(input().split()[::-1]))

十五、字符串练习题
1.

  • 题目描述:
    输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例
    如,输入”They are students.”和”aeiou”,
    则删除之后的第一个字符串变成”Thy r stdnts.”
  • 输入描述:
    每个测试输入包含2个字符串
  • 输出描述:
    输出删除后的字符串
  • 示例1:
输入
    They are students.
    aeiou
输出
    Thy r stdnts.

“”"

s1 = input('s1:')
s2 = input('s2:')

for i in s1:
    if i in s2:
        s1 = s1.replace(i,'')

print(s1)

2.设计一个程序,帮助小学生练习10以内的加法
详情:
- 随机生成加法题目;
- 学生查看题目并输入答案;
- 判别学生答题是否正确?
- 退出时, 统计学生答题总数,正确数量及正确率(保
留两位小数点);
“”"

import random

# count = 0
# right = 0
#
# while True:
#     a= random.randint(0,9)
#     b= random.randint(0,9)
#     print('%d + %d = ' %(a,b))
#     question = input('请输入您的答案:(q退出)')
#     result = a + b
#     if question == str(result):
#         print('回答正确')
#         right += 1
#         count += 1
#     elif question == 'q':
#         break
#     else:
#         print('回答错误')
#         count += 1
#
# percent = right / count
# print('测试结束,共回答%d道题,正确个数为%d,正确率为%.2f%%' %(count,right,percent * 100))

op = ['+','-','*','/']
s = random.choice(op)
print(s)

3.用户管理系统

import random

count = 0
right = 0

while True:
    a = random.randint(0, 9)
    # 作为除数
    b = random.randint(1, 9)
    op = ['+', '-', '*', '//']
    d = random.choice(op)
    print('%d %s %d = ' % (a, d, b))
    question = input('请输入您的答案: (q退出)')
    result1 = a + b
    result2 = a - b
    result3 = a * b
    result4 = a // b
    if question == str(result1):
        print('回答正确')
        right += 1
        count += 1
    elif question == str(result2):
        print('回答正确')
        right += 1
        count += 1
    elif question == str(result3):
        print('回答正确')
        right += 1
        count += 1
    elif question == str(result4):
        print('回答正确')
        right += 1
        count += 1
    elif question == 'q':
        break
    else:
        print('回答错误')
        count += 1

percent = right / count
print('测试结束,共回答%d道题,正确个数为%d,正确率为%.2f%%'
          % (count, right, percent * 100))
  • 添加用户:
    1). 判断用户是否存在?
    2). 如果存在, 报错;
    3). 如果不存在,添加用户名和密码分别到列表中;

  • 删除用户
    1). 判断用户名是否存在
    2). 如果存在,删除;
    3). 如果不存在, 报错;

  • 用户登陆

  • 用户查看

    1. 通过索引遍历密码
  • 退出
    “”"
    “”"
    1.系统里面有多个用户,用户的信息目前保存在列表里面
    users = [‘root’,‘westos’]
    passwd = [‘123’,‘456’]
    2.用户登陆(判断用户登陆是否成功
    1).判断用户是否存在
    2).如果存在
    1).判断用户密码是否正确
    如果正确,登陆成功,推出循环
    如果密码不正确,重新登陆,总共有三次机会登陆
    3).如果用户不存在
    重新登陆,总共有三次机会

“”"

# import random
# print(random.randint(1,50))

# users=['root','westos']
# passwd=['123','456']
# print('---------------登陆系统---------------')
# usertime=1
# passtime=1
# while usertime<=3:
#         a= input('请输入您的用户名:')
#         if a in users:
#                 while passtime<=3:
#                         if input('请输入您的密码:') == passwd[(users.index(a))]:
#                                 print('登陆成功')
#                                 exit()
#                         else:
#                                 print('密码错误')
#                                 passtime+=1
#                 print('密码输入错误次数已达限制,程序退出')
#                 exit()
#         else:
#                 print('用户不存在:')
#                 usertime+=1
# print('用户输入错误次数已达限制,程序退出')
users = ['root','westos']
passwds = ['123','456']

#尝试登录的次数
trycount = 0
while trycount < 3:
    #接收用户输入
    inuser = input('用户名:')
    inpasswd = input('密码:')
    #尝试次数加1
    trycount += 1
    if inuser in users:
        #先找出用户对应的索引值
        index = users.index(inuser)
        passwd = passwds[index]
        if inpasswd == passwd:
            print('%s登录成功' %(inuser))
            break
        else:
            print('%s登录失败:密码错误' %(inuser))
    else:
        print('用户%s不存在' %inuser)
else:
    print('尝试次数超过三次,请稍后登录...')

“”"
如何快速生成验证码,内推码
“”"

import random
import string

code_str = string.ascii_letters + string.digits
print(code_str)

def gen_code(len=4):
    return ''.join(random.sample(code_str,len))

# print(gen_code())
print([gen_code() for i in range(1000)])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值