Python、字符串

定义:字符串就是一系列字符。

在python中,用引号括起来的都是字符串,其中的引号可以是单引号也可以是双引号。
example:
”this is a string"
‘this is also a string’
单引号和双引号可以联合使用,彼此包含。
example:
“this ‘is’ a string"
‘“this is also” a string’

使用方法修改字符串的大小写:

  1. title():首字母大写
  2. upper():所有字母大写
  3. lower():所有字母小写
    example:
name= "ada love"
print(name.title())  #打印输出Ada love
print(name)          #打印输出ada love
print(name.upper())  #打印输出ADA LOVE
print(name.lower())  #打印输出ada love

合并(拼接)字符串

python使用加号(+)来合并字符串。
example:

first_name = "wang"
last_name = "hong"
name = fist_name+" "+last_name
welcome="hello,"+name.title()+"!"
print(welcome) #输出hello,Wang hong! 

使用制表符或换行符来添加空白

在这里插入图片描述

print("python")   #输出python
print("\tpython") #输出    python
print"languages:\npython\nc\njavaScript")
 """输出 python
   		 c
   		 JavaScript
   		 """

多行注释,用三个多引号包起来

删除空白

删除字符串首尾多余空白,strip()
删除字符串末尾空白,rstrip()
删除字符串开始空白,lstrip()
example:

english=" zhang san "
print(english)           #输出 zhang san (结尾到这个位置)
print(english.strip())   #输出zhang san(结尾到这个位置)
print(english.lstrip())  #输出zhang san (结尾到这个位置)
print(english.rstrip())  #输出 zhang san(结尾到这个位置)
print(english)           #输出 zhang san (结尾到这个位置,变量自身未曾改变)

字符串的基本操作

1、字符串的基本操作

>>> first='hello world'       #创建字符串hello world,并赋值给first
>>> first
'hello world'

所有的标准序列操作(如索引、分片、成员资格、求长度、最大值、最小值等等)对字符串同样适用
EXAMPLE:

>>> a="let's do it"
>>> a
"let's do it"
>>> a[:]                  #分片 a==a[:]
"let's do it"
>>> a[-3:]                #a[-3:]+[:-3]==a==a[:]
' it'
>>> a[:-3]
"let's do"
>>> a[-3:]='what'         #分片赋值不适用于字符串,因为字符串是不可变的。所以报错了   
Traceback (most recent call last):
  File "<pyshell#60>", line 1, in <module>
    a[-3:]='what'
TypeError: 'str' object does not support item assignment
如何在输出语句中输出两行?
>>> print("天王盖地虎宝塔镇河妖")
天王盖地虎宝塔镇河妖
>>> print("天王盖地虎\n宝塔镇河妖")
天王盖地虎
宝塔镇河妖

输出结果为两行,这里使用了转义字符\n,表示换行。Python中还有很多的转义字符,如下表:
在这里插入图片描述

字符串格式化

字符串格式化符号

字符串格式化使用操作符百分号(%)实现。
%也可用作求余运算。
example:


>>> print('hello,%s' % 'world')
hello,world
>>> print('小智今年%s岁了'% '10')
小智今年10岁了

下表不止字符串格式化,还有一些其他格式转换。
在这里插入图片描述

>>> print('小智今年%d岁了'% 10)
小智今年10岁了
>>> print('小智今年%s岁了'% 10)
小智今年10岁了
>>> 

由上述代码看出,整数既可以使用%d也可以用%s格式化。
如果要格式化实数(浮点型),就可以使用%f进行格式化,例如

>>> print('圆周率PI的值为:%f'% 3.14)
圆周率PI的值为:3.140000
>>> print('圆周率PI的值为:%2f'% 3.14)
圆周率PI的值为:3.140000
>>> print('圆周率PI的值为:%2.f'% 3.14)
圆周率PI的值为: 3
>>> print('圆周率PI的值为:%.2f'% 3.14)
圆周率PI的值为:3.14

%f可指定精度值。在Python中,使用%f时,如果不指定精度值,则默认输出6位小数。
指定精度值:以指定2位小数为例: %.2f
在python中,如果要输出%,就需要格式化字符%,从而使用%%。例如:

>>> print("输出百分号: %s " %  '%')
输出百分号: % 

字符串格式化元组

格式化操作符的右操作数可以是任意元素。如果是元组或映射类型(如字典),那么字符串格式化将会有所不同。如果有右操作数是元组,其中每一个元素都会被单独格式化,每个值都需要一个对应的转换说明符,即占位符。
example:

print('今年是%s年,中国%s,中国人口%s'%('2019','强大','数不清多少'))

今年是2019年,中国强大,中国人口数不清多少

>>> print('今年是%s年,中国%s,中国人口%s'%'2019','强大','数不清多少')
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    print('今年是%s年,中国%s,中国人口%s'%'2019','强大','数不清多少')
TypeError: not enough arguments for format string

由上述例子来看,在有多个占位符的字符串中,可以使用元组传入多个格式化值。如哦需要转换的元组作为表达式的一部分存在,就必须用圆括号括起来,否则会报错。

字符串方法

**find()**方法
str.find(str,beg=0,end=len(string))
str代表指定检索的字符串;beg代表开始索引,默认为0;end代表结束索引,默认为字符串的长度。返回结果为子串所在位置最左端索引,如果没有找到就返回-1.

>>> f='do it now'
>>> f.find('do')           #查找元素‘do’的位置,索引为起始0
0
>>> f.find(' ')            #查找元素空格,索引为2
2
>>> f.find('python')       #python该元素不存在字符串f中,所以返回-1
-1
>>> f.find('doo')          #不存在字符串中的元素或字符串返回-1
-1
>>> f.find('it',2)         #包含起始点的查找
3
>>> f.find('it',0,3)       #包含起始点和终点的查找
-1
>>> 

**join()**方法
用于将序列中的元素以指定字符连接成一个新字符串。
str.join(sequence)
此语法中,str代表指定检索的字符串,sequence代表要连接的元素序列。返回结果为指定字符连接序列中的元素后生成的新字符串。
join操作时,调用和被调用的对象都必须是字符串,任意一个不是字符串都会报错。

>>> num=[1,2,3,4,5]
>>> mark='+'
>>> mark.join(num)
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    mark.join(num)
TypeError: sequence item 0: expected str instance, int found
>>> mark.join(str(num))
'[+1+,+ +2+,+ +3+,+ +4+,+ +5+]'
>>> str(num)
'[1, 2, 3, 4, 5]'
>>> field=['1','2','3','4','5']
>>> mark.join(field)
'1+2+3+4+5'

low()方法
str.low():所有大写字母转换为小写

upper()方法
将字符串中小写字母转换为大写字母
str.upper()

swapcase()方法
字符串中大小写字母进行转换,将字符串中大写字母转换为小写、小写转换为大写。
str.swapcase()

replace()方法
把字符串中old(旧字符)替换成new(新字符),如果指定第3个参数max,替换次数不超过max次。
语法:str.replace(old,new[,max])

>>> now="1 Am your Father,You are my son"
>>> now.upper()
'1 AM YOUR FATHER,YOU ARE MY SON'
>>> now.lower()
'1 am your father,you are my son'
>>> now.swapcase()
'1 aM YOUR fATHER,yOU ARE MY SON'
>>> now.replace('Father','Mather',3)
'1 Am your Mather,You are my son'

split()方法
通过指定分隔符对字符串进行切片,如果参数num有指定值,就只分割num个子字符串。这是一个非常重要的字符串方法。是join()方法的逆方法,用来将字符串分割成序列。
语法:split(st=" ",num=string.count(str))
此语法中,str代表指定检索的字符串;st代表分隔符,默认为空格;num代表分割次数。返回结果为分割后的字符串列表。

>>> field="hello,i am your father"
>>> print('不提供任何分隔符分割后的字符串",field.split())
      
SyntaxError: EOL while scanning string literal
>>> print("不提供任何分隔符分割后的字符串",field.split())
不提供任何分隔符分割后的字符串 ['hello,i', 'am', 'your', 'father']
>>> print("根据i分割后的字符串:",field.split('i'))
根据i分割后的字符串: ['hello,', ' am your father']
>>> print("根据o分割后的字符串:",field.split('o'))
根据o分割后的字符串: ['hell', ',i am y', 'ur father']
>>> print("根据o分割1次后的字符串:",field.split('o',1))
根据o分割1次后的字符串: ['hell', ',i am your father']
>>> print(field)
hello,i am your father

strip()
strip()用于移除字符串头尾指定的字符(默认为空格)。
语法: str.strip([chars])
str:代表指定检索的字符串;chars代表移除字符串头尾指定的字符。返回结果为移除字符串头尾指定的字符后生成的新字符串。

>>> field='--do-it-now--'
>>> print("原字符串:"+field)
原字符串:--do-it-now--
>>> print("新字符串:"+field.strip('-'))
新字符串:do-it-now

由结果看出,strip方法值去除头尾匹配的字符,中间匹配的字符不会删除。

translate()
translate()方法根据参数table给出的表(包含256个字符)转换字符串的字符,将要过滤掉的字符放到del参数中。
语法:str.translate(table[,deletechars])
此语法中,str代表指定检索的字符串,table代表翻译表,翻译表通过maketrans方法转换而来。deletechars代表字符串中要过滤的字符列表。返回结果为翻译后的字符串。

>>> intab='adefs'
>>> outtab='12345'
>>> trantab=str.maketrans(intab,outtab)
>>> st='just do it'
>>> print('st调用translate方法后:',st.translate(trantab))
st调用translate方法后: ju5t 2o it
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值