python字符串的基本操作

# 字符串是python最常用的数据类型
# 因字符串是不可变的,所以除分片赋值外的所有标准序列操作对字符串适用
# temp1='just soso'
# print temp1[-1:]
# o
# temp1=[-2]=y
# print temp1
# File "C:/Users/Administrator/PycharmProjects/untitled1/Class2String/Str.py", line 7
# temp1=[-2]=y
# SyntaxError: can't assign to literal
#输出结果表明str类型的对象不支持更改

# 加入 可以使字符串输出两行
# print ('精诚所至 金石为开')
# 精诚所至
# 金石为开

# 字符串格式化符号
# print ('hello,%s'%'world')
# hello,world
# print ('小明今年%s岁了'%18)
# 小明今年18岁了
# %左边放置一个待格式化的字符串,右边放置的是希望格式化的值,格式化的值可以是一个字符串或数字

# print ('小明今年%s岁了'%18)
# 小明今年18岁了
# print ('小明今年%d岁了'%18)
# 小明今年18岁了
# 格式化实数(浮点数),使用%f
# print('圆周率PI的值为%f'%3.14)
# 圆周率PI的值为3.141500
#若不指定精度则默认为6位小数点

# 指定小数为例子
# print('圆周率PI的值为%.2f'%3.14)
# 圆周率PI的值为3.14

# 在python中若要输出百分号则要格式化百分号 例:
# print('同桌的智商比去年下降%.2f%%'%3.14)
# 同桌的智商比去年下降3.14%

# 字符串格式化元祖
# 如果右操作符是元祖,每个值都需要一个对应的转换说明符 例:
# print('今年是%s年,小明再大胃王比赛中获得了%s,总共吃了%d碗'%(2018,'冠军',20))
# 今年是2018年,小明再大胃王比赛中获得了冠军,总共吃了20碗

# 字段长度与宽度
# print('圆周率PI的值为%8.2f'%3.14)
# 圆周率PI的值为 3.14
# print('圆周率PI的值为%8.6f'%3.14)
# 圆周率PI的值为3.140000

# print('从元祖中获得字符串精度:%*.*s'%(10,5,'hello world'))
# 从元祖中获得字符串精度: hello

# 字符串方法
# find()方法,语法:
# str.find(str,beg=0,end=len(string))
# filed='do it,now'
# print filed.find('do')
# 0
# print filed.find('her')
# -1
# 有则返回索引,无则返回-1

#find方法可以接受参数,用于表示起始点和结束点
# print filed.find('now',6)
# 6
# print filed.find('now',7)
# -1

# print filed.find('now',4,6)
# -1
# print filed.find('it',1,5)
# 3

# join()方法 语法如下:
# str.join(seq)
# str代表指定检索的字符串,seq代表要连接的元素序列
# num=(1,2,3,4)
# remp='+'
# remp.join(num)
# Traceback (most recent call last):
# File "C:/Users/Administrator/PycharmProjects/untitled1/Class2String/Str.py", line 83, in <module>
# remp.join(num)
# TypeError: sequence item 0: expected string, int found

# num=('1','2','3')
# remp='+'
# print remp.join(num)
# 1+2+3
# 由输出结果可以看到,进行join操作调用和被调用必须都是字符串,任意一个不是字符串都会报错

# lower()方法用于将字符串中所有的大写字符转换为小写 语法如下:
# str.lower()
# filed='DO IT,NOW'
# print filed.lower()
# do it,now
# filed1='DO IT,NOW'
# print filed1.lower().find('it')
3
# print filed1.lower().find('it'.lower())
3

# upper()方法 语法如下:
# str.upper()
# filed='do it,now'
# print filed.upper()
# DO IT,NOW
# print filed.upper().find('IT')
# 3
# print filed.upper().find('IT'.upper())
# 3

# swapcase()方法 语法如下:
# file='just SO SO'
# print file.swapcase()
# JUST so so

#replace() 方法

# str.split(st='',num=string.cou
# split() 方法 语法如下:nt(str))
原文地址:https://www.cnblogs.com/hechenglong/p/8471046.html