Python中的字符串简介

这篇博客介绍了Python中的字符串,包括定义、特性、判断方法、去除开头和结尾的字符、搜索替换、对齐、统计、分离与连接等操作。还提供了一些实践练习,如判断回文数、变量名合法性、学生出勤记录分析以及字符串反转和剪切等。

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

1.字符串的定义:
将多行注释的内容赋值给一个变量,他就会变成一个字符串

a = "hello"
b = 'westos'
c = "what's up"
d = 'what\'s up'
e = """
        用户管理系统
        1.添加用户
        2.删除用户
        3.显示用户
"""
print(a)
print(b)
print(c)
print(d)
print(e)
print(type(e))

输出的结果:
hello
westos
what's up
what's up
用户管理系统
1.添加用户
2.删除用户
3.显示用户
<class 'str'>

2.字符串的特性
(1)索引:0,1,2,3,4,索引值默认从0开始

s = 'hello'
print(s[1])
print(s[0])
输出的结果:
e
h

(2)切片
1>切片的规则:

s[start:end:step]   ##从start开始到end-1结束,步长step
s = 'hello'
print(s[0:3])
print(s[0:4:2])
输出的结果:
 hel
 hl

2>显示所有字符:

print (s[:])
结果:hello

3>显示前三个字符:

print(s[:3])
结果:hel

4>字符串倒序输出

print(s[::-1])
olleh

5>除了第一个字符以外,其他全部输出

print(s[1:])
ello

6>重复

print(s * 10)
结果:
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello

7>连接

print('hello' + ' ' + 'world')
hello world

8>成员操作符,输出的是布尔值

s='hello'
print('h' in s)#判断s中是否含有h
ptint('q' in s)
Ture
False
  • 练习: 判断一个数是否为回文数:

     number = input('请输入一个数:')
          while  number[::-1] == number:
              print('这个数是一个回文数!')
              break
          else:
              print('这个数不是回文数')
    

标题:首字母大写,其余字母全部小写
3.字符串的判断
有is才是判断,没有就是将字符串变成相应的形式
(1)判断字符串里面每个元素是否为某种类型
1>判断是否为数字

 print('123'.isdigit())
 print('123abc'.isdigit())
输出:
 Ture
 False

2>判断是否为标题
标题:首字母大写,其余字母全部小写

 print('Hello'.istitle())
 print('HeLlo'.istitle())
 输出:
 Ture
 False

3>判断是否为大写或小写字母(所有的字母都匹配)

 print('hello'.upper())
 print('hello'.isupper())
 print('hElLo'.lower())
 print('hElLo'.islower())
 输出:
 HELLO
 False
 hello
 False

4>判断是否为字母或数字

 print('hello123'.isalnum())
 输出:
 True

5>判断是否为字母

 print('123'.isalpha())
 print('abc'.isalpha())
输出:
False
True

6>isinstance 判断字符串的类型

print(isinstance(1,int))
print(isinstance('a',str))
print(isinstance(1,str))
输出:
True
True
False

4.字符串去掉开头和结尾

s.strip()去掉开头和结尾
s.lstrip()去掉左边的(开头)
s.rstrip()去掉右边的(结尾) 括号里是要去掉的内容
 s = '    hello   '
 s.strip()  ##去掉开头和结尾的空格(括号中没有内容就表示空格)
 输出:
'hello'

 s.lstrip()##去掉左边即开头的空格
'hello   '

 s.rstrip() ##去掉结尾的空格
 '    hello'

 s = '    \nhello   '
 s.strip()  ##去掉开头和结尾的空格,\n表示换行,实际上也是空格
 'hello'

 s = '    \thello   ' ##\t是一个制表符的长度,即一个tab键的长度,可以在VIM里设置
 s.strip()
 'hello'
 
 s = 'helloh'
 s.strip('h')  ##去掉左右两边的h
 'ello'
 s.lstrip('he') ##去掉开头的he
 'lloh'

练习: 字符串匹配开头和结尾

 filename = 'hello.log'
 if filename.endswith('.log'):
     print(filename)
 else:
     print('error')
输出:
    hello.log
    
url1 = 'file:///mnt'
url2 = 'ftp://172.25.254.250/pub'
url3 = 'http://172.25.254.250/index.html'

if url3.startswith('http://'):
    print('爬取该网页')
else:
    print('错误网页')
输出:
   爬取该网页

练习: 判断变量名是否合法
1.变量名只能由字母、数字、下划线组成
2.只能以字母或下划线开头

 num = input('请输入一个变量:')
        if num.startswith('_') or num[:1].isalpha():
           print('首字母格式正确!')
             if num[1:].isalnum() \
                     or ('_') in num[:1] \
                     or num[1:].isdigit():
                print('合格')
             else:
                 print('不合格')
         else:
            print('首字母格式错误!')
             exit()

或者:

#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)

5.符串的搜索和替换

s.find找到子串并返回最小的索引
s.rfind找到子串,并返回最大的索引值
s.replace替换字符串中所有的指定字符串替换
s = 'hello world hello'
print(s.find('hello'))#find找到子串,并返回最小的索引
print(s.find('world'))
输出:
0
6
print(s.rfind('hello')) #rfind找到子串,并返回最大的索引值
输出:
12
print(s.replace('hello','westos')) #替换字符串中所有的‘hello’为‘westos’
输出:
westos world westos

6.字符串的对齐

左右都对齐center
左对齐ljust
右对齐rjust
print('学生管理系统'.center(30))
print('学生管理系统'.center(30,'*'))
print('学生管理系统'.center(30,'@'))
print('学生管理系统'.ljust(30,'*'))
print('学生管理系统'.rjust(30,'*'))
输出:
            学生管理系统				
************学生管理系统************
@@@@@@@@@@@@学生管理系统@@@@@@@@@@@@
************************学生管理系统
学生管理系统************************

7.字符串的统计

count统计个数
len统计长度
print('hello'.count('l'))
print('hello'.count('ll'))
print(len('hello'))
输出:
2
1
5

8.字符串的分离和连接
s.split(‘分离符’)
(‘用什么来连接,连接符’).join(要连接的字符串)
例1:

s = '172.25.254.250'
s1 = s.split('.')
print(s1)
print(s1[::-1])
输出:
[ '172', '25', '254', '250' ]
[ '250', '254', '25', '172' ] 

例2:

date = '2019-03-17'
date1 = date.split('-')
print(date1)
print(''.join(date1))
print('/'.join(date1))
输出:
[ '2019', '03', '17' ]
20190317
2019/03/17

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

s = input("请输入出勤记录("
          "'A':缺勤"
          "'L':迟到"
          "'P':到场 :")
if not ('A' or 'L' or 'P') in s:
    print('错误的格式')
else:
    if s.count ('A') <= 1 and s.count("LLL") <= 0 :
        print('优秀')
    else:
        print('没有奖励')

练习: 字符串的反转:
要求:输入
hello xiao mi
输出
mi xiao hello

简易版:
 str = input('请输入一串字符:')
 s = str.split()
 s1 = s[::-1]
 print ( ' '.join(s1))

优化版:
print (' '.join(input('请输入一串字符:').split()[::-1]))

剪切字符串
要求:输入
They are students.
aeiou
输出
Thy r stdnts.

s1 = input('请输入第一串字符:')
s2 = input('请输入第二串字符:')
for i in s1:
    if i in s2:
        s1 = s1.replace(i,' ')
print(s1)

补充快捷键:
ctrl+shift+end 选中全部

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值