Python3 基础数据类型-字符串类型及 *** 作

Python3 基础数据类型-字符串类型及 *** 作,第1张

 

 Python3 基础语法-字符串类型及 *** 作

        字符串是Python中最常用的数据类型之一。


 一、字符串类型基础 1.1 字符串的创建

        在Python中使用成对的单引号或成对的双引号创建字符串。使用三对单引号创建多行字符串。

s1 = "hello qianan"
print(s1)

s2 = 'hello qianan'
print(s2)

s3 = '''hello qianan'''
print(s3)

        注意:所有的单双号都是在英文状态下,并且必须是成对出现。

1.2 字符串的存储方式

        字符串是不可变的序列数据类型,不能直接修改字符串本身。

        字符串类型与数值类型的区别:

num = 200     #数值类型
num1 = "200"    #字符串类型

        实际上,对于数值类型而言,一个字节最大可以存储的数值是256,所以,num就存储在一个字节当中。但是,字符串本身就是序列数据结构,所以num1为“200”的模式是“2”、“0”、“0”分别存储在3个字节当中。

1.3 字符串的下标

        因为字符串是序列数据结构,所以,当我们要从某条字符串中提取某个字符就要通过索引(默认开始为0):

>>> s1 = "hello world"			
>>> s1[1]	# 从0开始,1是从左到右第二个			
'e'
>>> s1[10]
'd'
>>> s1[-1]  # -1就是从右到左倒数第一个
'd'
>>> s1[11]    # 超过字符串总长度(10),直接报错
Traceback (most recent call last):
  File "", line 1, in 
IndexError: string index out of range

        为什么说字符串是不可修改类型?下面我从一条字符串中索引一个字符后重新赋值,Python会直接报错:

>>> s2 = "hello world"
>>> s2[4] = 'l'

Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'str' object does not support item assignment

二、字符串类型的基本 *** 作 2.1 字符串切片

        slice()切片:

                start:起始位置,默认索引从0开始。

                stop:结束位置,默认最后一个元素。

                stop:步长,默认为1。

        slice()的方法定义:


class slice(object)
   slice(stop)
   slice(start, stop[, step])
 
   Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).

        切片实例:

        s3 = “hello world”  , 如何取出 “world”  

        代码如下:

>>> s3 = "hello world"
>>> s3[6:10]			# 注意,左闭右开
'worl'
>>> s3[6:11]
'world'
>>> s3[6:]				# 不写默认取到最后一位
'world'

        如何取出 “hlowrd” ?

        分析发现,它们在字符串s3中,是隔一个取一个,那么需要通过修改步长为2就可实现:

>>> s3[::2]
'hlowrd'

        s3 = “hello world”  ,将它逆向(倒叙)输出:

>>> s3[::-1]
'dlrow olleh'

2.2 字符串重组
  • 使用 + 号直接拼接

print('1'+'2')  # 12
  • %s、%d、%f

name = 'qianan'
age = 18
print('%s年龄%d'%(name,age)) 
  • str.format()

name = 'qianan'
age = 18
print('{}年龄{}'.format(name,18))
print('{1}年龄{0}'.format(18,name))
  • f'' 引号前加f

name = 'qianan'
age = 18
print(f'{name}的年龄是{age}')

三、 字符串常见 *** 作
  • S.find(sub) --> 返回该元素最小的索引。
    • 实际上,该方法与s.find()实现的功能一样,但是唯一不同的就是当元素不存在时,s.index()方法会报错。所以建议使用s.find()
>>> s4 = 'hello python'
>>> s4.find('e')
1
>>> s4.find('o')	# 当元素有多个时,返回最小索引
4
>>> s4.find('c')	# 找不到则为-1
-1
  • S.replace(old, new[, count]) --> 替换
>>> s5 = "hello python"
>>> s5.replace('l','a')  	# 将'l'替换成'a',全部替换
'heaao python'

>>> s5
'hello python'			 	# 注意:原来的字符串并没有被改变

>>> s5.replace('l','a',1)	# 只替换一个,则指定count参数为1即可
'healo python'
  • S.split(sep=None) --> 以sep来分割字符串,并返回列表。sep默认为None,分割默认为空格
>>> s6 = 'hello everyboby ye!'
>>> s6.split(' ')
['hello', 'everyboby', 'ye!']
  • S.startswith(prefix[, start[, end]]) --> 判断字符串是否以前缀开始,返回为bool值。
>>> s7 = "hello world"
>>> s7.startswith("he")
True
  • S.endswith(suffix[, start[, end]]) --> 判断字符串是否以尾缀结束,返回为bool值。
  • S.lower() --> 将字符串全部转为小写
  • S.upper() --> 将字符串全部转为大写
  • S.strip([chars]) --> 默认去掉字符串左右的空格
>>> s8 = '  hello world   '
>>> s8.strip()
'hello world'
  • S.isalpha() --> 判断字符串是否全为字母,返回的是bool值
  • S.isdigit()  --> 判断字符串是否全为数字,返回的是bool值
  • S.isalnum() --> 判断字符串是否全为数字或者字母,不存在特殊字符,返回的是bool值
  • S.join(iterable) --> 将序列中的元素以指定的字符连接生成一个新的字符串
li = ["你好","世界"]
s = ','.join(li)
print(s)

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/801679.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-07
下一篇 2022-05-07

发表评论

登录后才能评论

评论列表(0条)

保存