python中的字符串

一、字符串的定义方式

字符串是 Python 中最常用的数据类型。我们可以使用引号(‘或”)来创建字符串。
创建字符串很简单,只要为变量分配一个值即可。例如:

a = "hello"
b = 'westos'

二、字符串的特性

1.索引
索引:0,1,2,3,4……索引值是从0开始的
例如:

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

这里写图片描述
2.切片
切片的规则:s[start:end:step] 从start开始到end-1结束,步长为:step
例如:

s = 'hello'
print s[0:3]  
print s[0:4:2]
  • 显示所有字符 :s[:]
  • 显示前3个字符:s[:3]
  • 对字符串倒叙输出:s[::-1]
  • 除第一个字符以外,其他全部显示:s[1:]

这里写图片描述
3.重复
例如:将字符串“hello”显示十次

s ='hello'
print s * 10 

这里写图片描述

4.连接
例如 :将字符串‘hello’和‘world’连接起来

print 'hello ' + 'world'

这里写图片描述

5.成员操作符

s='hello'
print 'q' in s
print 'he' in s
print 'aa' in s

这里写图片描述

三、字符串的用法

1.字符串的统计
例如:

print 'helloooo'.count('o')

这里写图片描述

2.字符串的搜索和替换
搜索:find:找到字符串,并返回最小的索引
替换:replace

s = 'hello world'
print len(s)

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

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

这里写图片描述
3.字符串的分离和连接
1)分离
例如:

s = '172.25.254.250'
s1 = s.split('.')
print s1

date = '2018-8-27'
date1 = date.split('-')
print date1

这里写图片描述

2)连接
例如:

date = '2018-8-27'
date1 = date.split('-')
print date1
print ''.join(date1)
print '/'.join(date1)

print '/'.join('hello')

这里写图片描述
4.字符串开头和结尾匹配
例如:

s = 'hello.jpg'
print s.endswith('.png')    # 找出字符串是否以XXX结尾

url1 = 'http://www.baidu.com'
url2 = 'file:///mnt'

print url1.startswith('http://')
print url2.startswith('f')

这里写图片描述
5.字符串判断是否是大小写、数字或是标题
判断类型时,若有一个元素不满足,就返回False

print '123'.isdigit()
print '123w'.isdigit()
# tile:标题 判断某个字符串是否是标题(首字母大写的就是标题)
print 'hello'.istitle()
print 'Hello'.istitle()
print 'hello'.upper()#将小写转换成大写
print 'HELLO'.lower()#将大写转换成小写
print 'hello'.isalnum()
print '123'.isalpha() #是否是字母
print '123'.isalnum()
print 'qqq'.isalnum() #是否有字母和数字

这里写图片描述

四、示例

示例【1】:输入一行字符,统计其中有多少个单词,每两个单词之间以空格隔开,如输入:This is a c++ program.输出:There are 5 words in the line

a = raw_input('请输入一行英文字符:')
li = a.split()
b = len(li)
print 'There are %d words in the line' % b

这里写图片描述

示例【2】:给出一个字符串,在程序中赋初值为一个句子,例如“he threw three free throws”,自编函数完成下面的功能:求出字符列表中字符的个数(对于例句,输出为26)

a = raw_input('请输入一行字符:')
b = len(a)
print '%d' % b

这里写图片描述

示例【3】:给定一个字符串来代表一个学生的出勤记录,这个记录仅包含以下三个字符:‘A’:Absent,缺勤 ‘L’:Late,迟到 ‘P’:Present,到场,如果一个学生的出勤记录中不超过一个‘A’(缺勤)并且不超过两个连续的‘L’(迟到),那么,这个学生会被奖赏。示例1:输入:”PPALLP”输出:True 示例2:输入:“PPALLL” 输出False

s = str(raw_input('学生的出勤记录'))
if (s.count('A') <= 1 and s.count('LLL') == 0):
    print 'True'
else:
    print 'False'

这里写图片描述
这里写图片描述
示例【4】:判断一个数是否是回文数。例如:输入:121,输出也是121,像这样的数就是回文数

num = raw_input('Num:')
if num == num[::-1]:
    print 'True'
else:
    print 'False'

这里写图片描述
这里写图片描述

示例【5】:打印菱形

n = int(raw_input('Num:'))
for i in range(1,n):
    print ('*' * i).center(n,' ')
for i in range(n,0,-1):
    print ('*' * i).center(n,' ')

这里写图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值