小菜鸟的python进阶之路 ------- 字符串

字符串

  • 定义方法
  • 字符串的特性
  • 字符串的类型判断(可以补全)
  • 字符串开头和结尾的判断
  • 字符串的操作

 

1.定义方式

a = 'hello'
b = 'what\'s up'
c = "what's up"

2.字符串的特性

  • 索引
  • 切片
  • 重复
  • 连接
  • 成员操作符
  • 迭代


(1)索引

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

(2)切片

规则:s[start:end:step] 从start到step-1,步长step

#显示所有字符
print(s[:])
#显示前3个字符
print(s[:3])
#对字符串倒叙输出
print(s[::-1])
#除了第一个字符以外,其他全部显示
print(s[1:])

(3)重复

print(s*3)

(4)连接

print(s + 'hello')

(5)成员操作符

print('d' in s)

(6)迭代

for in s:
  print i


练习1:回文数判断

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

"""

num = input("请输入要判断的数:")

if num == num[::-1]:
    print("这个数是回文数")
else:
    print("这个数不是回文数")

 

3.字符串的类型判断(可以补全)

  • isdigit()     
  • istittle()
  • isupper()
  • islower()
  • isalpha()
  • isalnum()

判断字符串里每个元素是否为 什么类型,一旦有一个元素不满足,就返回False

 

1.isdigit()  判断是否是数字

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

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

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

3.isupper()判断是否是大写

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

4.islower()判断是否是小写

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

5.isalpha()判断是否是字母组成

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

6.isalnum()判断是否是字母与数字混合组成

print('hello123'.isalnum())


4.字符串开头和结尾的判断

  • startswith()
  • endswith()

1.startswith()判断是否以什么开头

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('未找到网页')

2.endswith()判断字符串是否以什么结尾

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


练习2:变量名是否合法判断

name = input("请输入一个变量名:")

if name[0].isalpha() or name[0]=='_':
    for i in name[1:]:
        if i.isalnum() or i == '_':
            continue
        else:
            print("变量名不合法!")
            break
    else:
        print("这是合法的变量名!!")
else:
    print("不合法的变量名!!")

5.字符串的操作

  • 字符串除去两边空格
  • 查找字串
  • 字符串的替换
  • 字符串的居中,左右对齐
  • 字符串的长度
  • 字符串中字符个数的统计
  • 字符串的分离
  • 字符串的连接

1.字符串除去两边空格

  • strip()   
  • lstrip() 
  • rstrip() 

1.strip()    ##去除两边的空格

>>> '   hello   '.strip()
'hello'

2.lstrip()   ##去除左边的空格

>>> '   hello   '.lstrip()
'hello   '

3.rstrip()   ##去除右边的空格

>>> '   hello   '.rstrip()
'   hello'

2.查找字串

  • find() 
  • rfind()

1.find()  ##返回最小索引,找不到返回-1

s = 'hello world hello'

#find找到子串,并返回最小的索引
print(s.find('hello'))
print(s.find('world'))

2.rfind()  ##返回最大索引,找不到返回-1

s = 'hello world hello'

#rfind找到子串,并返回最大索引
print(s.rfind('hello'))


3.字符串的替换

  • replace()
#替换字符串中所有的'hello'为'westos'
print(s.replace('hello','westos'))

4.字符串的居中,左右对齐

  • center()
  • ljust()
  • rjust()

1.center(30,'*')#居中

>>> '  hello  '.center(30,'*')
'**********  hello  ***********'

2.ljust()#居左

>>> '  hello  '.ljust(30)
'  hello                       '

3.rjust()#居又

>>> '  hello  '.rjust(30)
'                       hello  '

5.字符串的长度

  • len()
>>> len('hello')
5

6.字符串中字符个数的统计

  • count()
>>> 'hello'.count('l')
2

7 .字符串的分离

  • split()
>>> 'hello'.split()
['hello']

8.字符串的连接

  • join()
>>> str = ['hello','word']
>>> ' '.join(str)
'hello word'


练习3:统计学生的出勤

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

代码:
s = input("请输入该学生的出勤记录:")
print(s.count('A') <= 1 and s.count('LLL') == 0)

练习4:小米面试题

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

s = input("请输入一个句子(只包含字母和空格):")
print(' '.join(s.split(" ")[::-1]))



练习4:字符串的删除

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


str1 = input("input:")
str2 = input("input:")

for i in str1:
    if i in str2:
        str1 = str1.replace(i,'')
print(str1)


 


 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值