亲宝软件园·资讯

展开

Python中常用的8种字符串操作方法

人气:1

拼接字符串

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

语法格式: 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

参数说明

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

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

总结

以上所述是小编给大家介绍的Python中常用的8种字符串操作方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论