Python中有哪些字符串操作方法

发布时间:2021-01-06 16:24:44 作者:Leah
来源:亿速云 阅读:119

Python中有哪些字符串操作方法?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

Python中有哪些字符串操作方法

拼接字符串

使用“+”可以对多个字符串进行拼接

语法格式: str1 + str2

>>> str1 = "aaa"
>>> str2 = "bbb"
>>> print(str1 + str2)
aaabbb

需要注意的是字符串不允许直接与其他类型进行拼接,例如

>>> num = 100
>>> str1 = "hello"
>>> print(str1 + num)
Traceback (most recent call last):
 File "<pyshell#5>", line 1, in <module>
 print(str1 + num)
TypeError: can only concatenate str (not "int") to str

上面这种情况我们可以将num转换为字符串再进行拼接

>>> num = 100
>>> str1 = "hello"
>>> print(str1 + str(num))
hello100

这样就不会报错了

计算字符串的长度

在Python中使用len()函数来计算字符串的长度

语法格式: len(string)

>>> str1 = "hello"
>>> len(str1)
5
>>> str2 = "你好"
>>> len(str2)
2
>>> str3 = "1111"
>>> len(str3)
4

从上面的结果我们可以看出,在默认情况下,len函数在计算字符串的长度时,无论是数字,字母还是多字节的汉字都认为是一个字符。

为什么说是默认情况下呢,因为在实际开发中,可能因为我们采取的编码不同,字符串实际所占的字节数也不同。

这时我们可以通过使用encode()方法进行编码后再进行获取长度。

例如:

>>> str1 = "你好"
>>> len(str1)
2
>>> len(str1.encode('gbk'))
4
>>> len(str1.encode('utf-8'))
6

截取字符串

语法格式: string[start : end : step]

参数说明

>>> str1 = "hello world!"
>>> str1[1]  #截取第2个字符
'e'
>>> str1[2:] #从第3个字符开始截取
'llo world!'
>>> str1[:4]
'hell'
>>> str1[1:5]
'ello'
>>> str1[-1] #截取最后一个字符
'!'
>>> str1[2:-2]
'llo worl'

注意:字符串的索引是从0开始的

分割字符串

python中分割字符串是使用split()方法把字符串分割成列表

语法格式 : str.split(sep, maxsplit)

参数说明:

>>> str1 = "i am a good boy!"
>>> str1.split() #采用默认分割符进行分割
['i', 'am', 'a', 'good', 'boy!']
>>> str1.split(" ") #采用空格进行分割
['i', 'am', 'a', 'good', 'boy!']
>>> str1.split(" ", 3) #采用空格进行分割,并且只分割前3个
['i', 'am', 'a', 'good boy!']

注意默认情况下按空格分割

检索字符串

python中字符串的查找方法

1、count()方法

语法格式 : str.count(sub[, start[, end]])

作用:用于检索指定字符串在另一个字符串中出现的次数,如果检索的字符串不存在则返回0,否则返回出现的次数。

参数说明

>>> str1 = "hello world"
>>> print(str1.count('o'))
2

2、find()方法

语法格式 : str.find(sub[, start[, end]])

作用:检索是否包含指定的字符串,如果检索的字符串不存在则返回-1,否则返回首次出现该字符串时的索引。

>>> str1 = "hello world!"
>>> str1.find('wo')
6

3、index()方法

语法格式 : str.index(sub[, start[, end]])

作用:和find方法类似,也用于检索是否包含指定的字符串,使用index方法,当指定的字符串不存在时会抛异常。

>>> str1 = "hello world!"
>>> str1.index('w')
6
>>> str1.index('m')
Traceback (most recent call last):
 File "<pyshell#6>", line 1, in <module>
 str1.index('m')
ValueError: substring not found
>>> str1.find('m')
-1

4、startswith()方法

语法格式 : str.startswith(prefix[, start[, end]])

作用:检索字符串是否以指定的字符串开头,如果是则返回true,否则返回false。

>>> str1 = "hello world!"
>>> str1.startswith('hello')
True
>>> str1.startswith('hi')
False
>>>

5、endswith()方法

语法格式 : str.endswith(prefix[, start[, end]])

作用:检索字符串是否以指定的字符串结尾,如果是则返回true,否则返回false。

>>> str1 = "hello world!"
>>> str1.endswith('world!')
True
>>> str1.endswith('haha')
False

字符串的大小写转换

1、lower()方法

语法格式 : str.lower()

作用:将字符串中的大写字母转换为小写字母

>>> str1 = "Hello World!"
>>> str1.lower()
'hello world!'

2、upper()方法

语法格式 : str.upper()

作用:将字符串中的小写字母转换为大写字母

>>> str1 = "Hello World!"
>>> str1.upper()
'HELLO WORLD!'

去除字符串中的空格和特殊字符

开发中,我们会遇到这样的需求,字符串前后(左右侧)不允许出现空格和特殊字符或者将用户输入的字符串中误输入的空格去除掉。这时我们就需要用到strip函数。

1、strip()方法

语法格式 : str.strip([chars])

作用:去除字符串前后(左右侧)的空格或特殊字符

>>> str1 = " hello world! "
>>> str1.strip()
'hello world!'
>>> str2 = "#hello world#@#"
>>> str2.strip('#')
'hello world#@'
>>> str3 = "@hello world!@."
>>> str3.strip('@.')
'hello world!'

2、lstrip()方法

语法格式 : str.lstrip([chars])

作用:去除字符串前面(左侧)的空格或特殊字符

>>> str1 = " hello world! "
>>> str1.lstrip()
'hello world! '
>>> str2 = "#hello world#@#"
>>> str2.lstrip('#')
'hello world#@#'
>>> str3 = "@.hello world!@."
>>> str3.lstrip('@.')
'hello world!@.'

3、rstrip()方法

语法格式 : str.rstrip([chars])

作用:去除字符串后面(右侧)的空格或特殊字符

>>> str1 = " hello world! "
>>> str1.rstrip()
' hello world!'
>>> str2 = "#hello world#@#"
>>> str2.rstrip('#')
'#hello world#@'
>>> str3 = "@.hello world!@."
>>> str3.rstrip('@.')
'@.hello world!'

格式化字符串

所谓格式化字符串就是先制定一个模板,在模板中预留几个空位,然后根据需要填上相应的内容。

使用“%”操作符

语法格式: '%[-][+][0][.n]格式化字符'%exp

参数说明

Python中有哪些字符串操作方法

exp:要转换的项,如果要指定的项有多个,需要通过元组的形式进行指定,但不能使用列表。

>>> template = '学号:%d,姓名:%s,班级:%s'
>>> print(template% (123,'张三','一年级'))
学号:123,姓名:张三,班级:一年级

关于Python中有哪些字符串操作方法问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. Python冷干货—字符串操作方法
  2. python字符串截取的操作方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 字符串 中有

上一篇:python中有哪些基础函数

下一篇:Mysql中有哪些时间日期函数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》