一.字符串的定义方式
a = "hello"
b = 'westos'
c = "what's up"
d = """
用户管理
1.添加用户
2.删除用户
3.显示用户
"""
print a
print b
print c
print d
二.字符串的搜索和替换
代码:
s = 'hello world'
#print len(s)
# find找到字符串 并返回最小的索引
print s.find('hello')
print s.find('world')
print s.replace('hello','westos')
三.字符串的特性
代码:
# 索引:0,1,2,3,4 索引值是从0开始
s = 'hello'
print s[0]
print s[1]
# 切片
print s[0:3] # 切片的规则:s[start:end:step] 从start开始到end-1结束,步长:step
print s[0:4:2]
# 显示所有字符
print s[:]
# 显示前3个字符
print s[:3]
# 对字符串倒叙输出
print s[::-1]
# 除了第一个字符以外,其他全部显示
print s[1:]
# 重复
print s * 10
# 连接
print 'hello ' + 'world'
# 成员操作符
print 'q' in s
print 'he' in s
print 'aa' in s
四.字符串的统计
print 'helloooo'.count('o')
五.字符串开头和结尾匹配
代码:
s = 'hello.jpg'
# 找出字符串是否以XXX结尾
print s.endswith('.png')
url1 = 'http://www.baidu.com'
url2 = 'file:///mnt'
print url1.startswith('http://')
print url2.startswith('f')
六.字符串的分离和连接
代码:
# split对于字符串进行分离,分割符为'.'
s = '172.25.254.250'
s1 = s.split('.')
print s1
date = '2018-8-27'
date1 = date.split('-')
print date1
# 连接
print ''.join(date1)
print '/'.join(date1)
print '/'.join('hello')
七.字符串判断是否大小写或数字
代码:
# 判断字符串里面的每个元素是否为什么类型
# 一旦有一个元素不满足,就返回False
print '123'.isdigit()
print '123abc'.isdigit()
# title:标题 判断某个字符串是否为标题(第一个首字母大写,其余字母小写)
print 'Hello'.istitle()
print 'HeLlo'.istitle()
print 'hello'.upper()
print 'hello'.islower()
print 'HELLO'.lower()
print 'HELLO'.isupper()
print 'hello'.isalnum()
print '123'.isalpha()
print 'qqq'.isalpha()
八.练习
1.变量名是否合法?
# # 变量名可以由字母,数字或者下划线组成;
# # 变量名只能以字母或者下划线开头;
# s = "hello@"
# 1. 判断变量名的第一个元素是否为字母或者下划线; s[0]
# 2. 如果第一个元素符合条件, 判断除了第一个元素的其他元素;s[1:]
代码:
while True:
s = raw_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
2.回文数判断
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
代码:
num = raw_input('Num:')
if num == num[::-1]:
print '这是一个回文数'
else:
print '这不是一个回文数'
3.输入一行字符,统计其中有多少个单词,每两个单词之间以空格隔开。
如输入: 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
4.给出一个字符串,在程序中赋初值为一个句子,例如"he threw three free throws",
自编函数完成下面的功能:
1)求出字符列表中字符的个数(对于例句,输出为26)
代码:
a = raw_input('请输入一行字符:')
b = len(a)
print '%d' % b