Python之字符串的特性及常用方法
字符串的特性
索引: (索引是从0开始)
s='hello'
print(s[0])
print(s[4])
print(s[-1]) #拿出最后一个字符
h
o
o
1
2
3
4
5
6
7
8
截取s[start:stop:step] 从start开始到stop结束,步长为step
print(s[0:3])
print(s[0:4:2])
print(s[:]) #显示所有的字符
print(s[:3]) #显示前3个字符
print(s[1:]) #除了第一个字符之外的其他全部字符
print(s[::-1]) #字符串的翻转
hel
hl
hello
hel
ello
olleh
1
2
3
4
5
6
7
8
9
10
11
12
13
重复
print(s * 10)
hellohellohellohellohellohellohellohellohellohello
1
2
3
连接
print('hello ' + 'python')
hellopython
1
2
3
成员操作符
print('he' in s)
print('aa' in s)
print('he' not in s)
True
False
False
1
2
3
4
5
6
7
for循环遍历
for i in s:
print(i)
h
e
l
l
o
1
2
3
4
5
6
7
8
-------------练习1------------
判断一个整数是否是回文数。
# nmb=input('请输入一个数:')
# nmbs=nmb[ : :-1]
# if(nmb == nmbs):
# print('此数是回文数')
# else:
# print('此数不是回文数')
1
2
3
4
5
6
不用字符串特性
# nmb = input('输入数字:')
# c = len(nmb)
# b = int(c / 2)
# a = 0
# for j in range(b):
# if (nmb[a] != nmb[c - 1 - a]):
# print('不是回文数')
# break
# else:
# print('是回文数')
1
2
3
4
5
6
7
8
9
10
字符串的常用方法
判断是否是标题、大写、小写、以及大小写、标题的转换、将字符串的首字母大写其余字母全部小写
str.istitle()
str.isupper()
str.islower()
str.title() #将字符串中的所有单词的首字母大写,其余字母全部小写;单词以任何标点符号区分的
str.captialize() #将字符串的首字母大写,其余字母全部小写
str.upper()
str.lower()
>>> 'Hello'.istitle()
True
>>> 'hello'.istitle()
False
>>> 'hello'.isupper()
False
>>> 'Hello'.isupper()
False
>>> 'HELLO'.isupper()
True
>>> 'hello'.islower()
True
>>> 'HELLO'.islower()
False
>>> 'HELLO'.lower()
'hello'
>>> 'hello'.upper()
'HELLO'
>>> 'hello'.title()
'Hello'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
前缀和尾缀的匹配
filename = 'hello.logrrrr'
if filename.endswith('.log'):
print(filename)
else:
print('error.file')
error.file
url = 'https://172.25.254.250/index.html'
if url.startswith('http://'):
print('爬取网页')
else:
print('不能爬取')
不能爬取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
去除左右两边的空格,空格为广义的空格 包括:\t \n
>>> s = ' hello '
>>> s
' hello '
>>> s.lstrip()
'hello '
>>> s.rstrip()
' hello'
>>> s.strip()
'hello'
>>> s = '\t\thello \n\n'
>>> s
'\t\thello \n\n'
>>> s.strip()
'hello'
>>> s.rstrip()
'\t\thello'
>>> s.lstrip()
'hello \n\n'
>>> s = 'helloh'
>>> s.strip('h')
'ello'
>>> s.strip('he')
'llo'
>>> s.lstrip('he')
'lloh'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
字符串的判断
str.isdigit() #全数字
str.isalpha() #全字母
str.isalnum() #只有数字和字母
-------------练习--------------
判断变量名定义是否合法:
1.变量名可以由字母 数字 下划线组成
2.变量名只能以字母和或者下划线开头
sname = input('请输入变量名:')
if not (sname[0].isalpha()) or sname[0] == '_':
print('illegal')
else:
a =0
for i in sname:
if sname[a] =='_' or sname[a].isalnum():
a += 1
else:
print('illegal')
break
else:
print('合法')
----------------OR--------------------
# while True:
# s = input('变量名:')
# if s == 'exit':
# print('exit')
# 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))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
字符串的对齐
print('jjj'.center(30))
print('jjj'.center(30,'*'))
print('jjj'.ljust(30,'#'))
print('jjj'.rjust(30,'$'))
jjj
*************jjj**************
jjj###########################
$$$$$$$$$$$$$$$$$$$$$$$$$$$jjj
1
2
3
4
5
6
7
8
9
字符串的搜索和替换
s = 'hello world hello'
1
#find找到子字符串,并返回最小的索引
print(s.find('hello'))
print(s.find('world'))
print(s.rfind('hello'))
1
2
3
#替换字符串中的hello为westos
print(s.replace('hello','westos'))
1
字符串的统计及串长
print('hello'.count('l')) 2
print('hello'.count('ll')) 1
print(len('westosssss')) 10
1
2
3
4
字符串的分割和连接
#分割 通过指定的连接符进行
s = '172.25.254.250'
s1 = s.split('.')
print(s1)
print(s1[::-1])
date = '2019-05-24'
date1 = date.split('-')
print(date1)
1
2
3
4
5
6
7
8
#连接 通过指定的连接符,连接每个字符串
print(''.join(date1))
print('/'.join(date1))
print('~~'.join('hello'))
1
2
3
-------------练习--------------
#小米笔试练习:给定一个句子(只有字母和空格,单词用一个空格隔开)将句子中单词的位置反转
# while True:
# str = input('请输入句子: ')
# if str == 'exit':
# exit()
# else:
# str1 = str.split(' ')
# print(' '.join(str1[::-1]))
1
2
3
4
5
6
7
-------------练习---------------
#设计程序:帮助小学生练习10以内的加法
#detail:随机生成加法题目,学生查看题目并输入答案,判别,退出统计答题总数,正确数,正确率
# import random
# a=0
# b=0
# while True:
# str = input('答题:y or n ')
# if str == 'n':
# print('答题总数为%d,正确数为%d,正确率为%.2f' %(a,b,b/a))
# exit()
# else:
# nmb1 = random.randint(0, 10)
# nmb2 = random.randint(0, 10)
# jug = nmb1 + nmb2
# print('%d + %d=' % (nmb1, nmb2), end='')
# ans = int(input())
# if ans == jug:
# b+=1
# print('正确')
# else:
# print('错误')
# a+=1
#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
------------练习-------------
#设计程序:百以内的算术练习
#功能:提供10道±*/题目,练习者输入答案,程序自动判断并显示
import random
opt = ['+', '-', '*', '/']
print('开始答题:')
for i in range(10):
nmb1 = random.randint(0, 100)
nmb2 = random.randint(0, 100)
f = random.choice(opt)
print('%d%s%d= ' % (nmb1, f, nmb2),end='')
ans = int(input( ))
if (f == opt[0]):
jug = nmb1 + nmb2
elif (f == opt[1]):
jug = nmb1 - nmb2
elif (f == opt[2]):
jug = nmb1 * nmb2
else:
jug = nmb1 / nmb2
if ans == jug:
print('正确')
else:
print('错误')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Python之字符串的特性及常用方法的更多相关文章
- python 字符串的特性
#######str字符串#####str字符判断大小写 url1 = 'http://www.cctv.com' url2 = 'file:///mnt' print url1.startsw ...
- Python中字符串的使用
这篇文章主要介绍python当中用的非常多的一种内置类型——str.它属于python中的Sequnce Type(序列类型).python中一共7种序列类型,分别为str(字符串),unicode( ...
- C、C++、C#、Java、php、python语言的内在特性及区别
C.C++.C#.Java.PHP.Python语言的内在特性及区别: C语言,它既有高级语言的特点,又具有汇编语言的特点,它是结构式语言.C语言应用指针:可以直接进行靠近硬件的操作,但是C的指针操作 ...
- Java基础-字符串(String)常用方法
Java基础-字符串(String)常用方法 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.java的API概念 Java的API(API:Application(应用) Pr ...
- 【转】Python格式化字符串str.format()
原文地址:http://blog.xiayf.cn/2013/01/26/python-string-format/ 每次使用Python的格式字符串(string formatter),2.7及以上 ...
- Python——拼接字符串
Python中可以对字符串进行拼接: 1. 使用字符串拼接运算符: + >>> "Hello" + "World" 'HelloWorld' ...
- python之time和datetime的常用方法
python之time和datetime的常用方法 一.time的常用方法: import time,datetime # 时间有三种展现方式:时间戳,时间元组,格式化的时间print(time. ...
- Python 3.8 新特性来袭
Python 3.8 新特性来袭 Python 3.8是Python语言的最新版本,它适合用于编写脚本.自动化以及机器学习和Web开发等各种任务.现在Python 3.8已经进入官方的beta阶段,这 ...
- python学习2—python3特性与各种运算符
python学习2—python3特性与各种运算符 python3与python2相比具有的新特性 在python2中可以使用__future__模块调用python3的特性 print()函数必须带 ...
随机推荐
- 【CERC2008】【BZOJ4319】Suffix reconstruction
Description 话说练习后缀数组时,小C 刷遍 poj 后缀数组题. 各类字符串题闻之丧胆.就在准备对敌方武将发出连环杀时,对方一记无中生有,又一招顺 手牵羊.小C 程序中的原字符数组就被牵走 ...
- IT咨询顾问:一次吐血的项目救火 java或判断优化小技巧 asp.net core Session的测试使用心得 【.NET架构】BIM软件架构02:Web管控平台后台架构 NetCore入门篇:(十一)NetCore项目读取配置文件appsettings.json 使用LINQ生成Where的SQL语句 js_jquery_创建cookie有效期问题_时区问题
IT咨询顾问:一次吐血的项目救火 年后的一个合作公司上线了一个子业务系统,对接公司内部的单点系统.我收到该公司的技术咨询:项目启动后没有规律的突然无法登录了,重新启动后,登录一断时间后又无法重新登 ...
- 使用fiddler将网站上的css js重定向至本地文件
使用fiddler将网站上的css js重定向至本地文件,进行在线调试 https://github.com/annnhan/ReRes 1条回复 这是一篇写给公司负责切图和调样式的前端的文章.主要适 ...
- lua-5.2.3编译问题记录"libreadline.so: undefined reference to `PC'"
作者:zhanhailiang 日期:2014-10-21 [root@~/software]# cd lua-5.2.3 [root@~/software/lua-5.2.3]# make linu ...
- Codeforces(429D - Tricky Function)近期点对问题
D. Tricky Function time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- [办公自动化]凭证纸打印 IE 默认设置
财务人员需要打印凭证纸,系统windows7,打印机HP P1106 在自定义纸张类型中设置凭证纸. 属性,打印首选项,“纸张和质量”选卡处,单击自定义(需要管理员权限) 输入“PZ” 宽148 高2 ...
- bzoj 1924 所驼门王的宝藏
题目大意: 有一个r*c的矩阵,上面有n个点有宝藏 每个有宝藏的点上都有传送门 传送门有三种:第一种可以传到该行任意一个有宝藏的点,第二种可以传到该列任意一个有宝藏的点,第三种可以传到周围的八连块上有 ...
- BZOJ_1229_[USACO2008 Nov]toy 玩具_三分+贪心
BZOJ_1229_[USACO2008 Nov]toy 玩具_三分+贪心 Description 玩具 [Chen Hu, 2006] Bessie的生日快到了, 她希望用D (1 <= D ...
- rsync单向同步
系统版本:Centos X64 6.4(最小化安装) 先安装依赖包 [root@localhost ~]# yum install vim wget lsof gcc make cmake makec ...
- apache相关补充
apache相关补充 sendfile机制 1)不用sendfile的传统网络传输过程: read(file, tmp_buf, len) write(socket, tmp_buf, len) 2) ...