所谓字符串,就是由零个或多个字符组成的有限序列。在Python程序中,如果我们把单个或多个字符用单引号或者双引号包围起来,就可以表示一个字符串。
In [6]: s1 = 'hello, world!'
In [7]: s2 = "hello, world!"
In [8]: # 以三个双引号或单引号开头的字符串可以折行
In [9]: s3 = """
...: hello,
...: world!
...: """
In [10]: print(s1, s2, s3, end='')
hello, world! hello, world!
hello,
world!
# 可以在字符串中使用(反斜杠)来表示转义,也就是说后面的字符不再是它原来的意义,例如:n不是代表反斜杠和字符n,而是表示换行;而t也不是代表反斜杠和字符t,而是表示制表符。所以如果想在字符串中表示单引号' 要写成',同理想表示反斜杠要写成。
In [13]: s1 = ''hello, world!''
In [14]: s2 = 'nhello, world!n'
In [15]: print(s1, s2, end='')
'hello, world!'
hello, world!
如果不希望字符串中的表示转义,我们可以通过在字符串的最前面加上字母r来加以说明。
In [18]: s1 = r''hello, world!''
In [19]: s2 = r'nhello, world!n'
In [20]: print(s1, s2, end='')
'hello, world!' nhello, world!n
In [21]:
Python为字符串类型提供了非常丰富的运算符,我们可以使用+运算符来实现字符串的拼接,可以使用*运算符来重复一个字符串的内容,可以使用in和not in来判断一个字符串是否包含另外一个字符串(成员运算),我们也可以用[]和[:]运算符从字符串取出某个字符或某些字符(切片运算),切片有三个参数,分别是(起始位置,结束位置,步长),截取的字符串包左不包右,代码如下所示。
In [1]: s1 = 'hello ' * 3
In [2]: print(s1)
hello hello hello
In [3]: s2 = 'world'
In [4]: s1 += s2
In [5]: print(s1)
hello hello hello world
In [6]: print('ll' in s1)
True
In [7]: print('python' in s1)
False
In [8]: s3 = 'abc123456'
# 从字符串中取出指定位置的字符(下标运算)
In [9]: print(s3[2])
c
# 字符串切片(从指定的开始索引到指定的结束索引)
In [10]: print(s3[2:5])
c12
In [11]: print(s3[2:])
c123456
In [12]: print(s3[2::2])
c246
In [13]: print(s3[::2])
ac246
# 这种方法可以用于字符串的逆序
In [14]: print(s3[::-1])
654321cba
In [15]: print(s3[-3:-1])
45
In [19]: str1 = 'hello, world!'
# 通过内置函数len计算字符串的长度
In [20]: print(len(str1))
13
# 获得字符串首字母大写的拷贝
In [21]: print(str1.capitalize())
Hello, world!
# 获得字符串每个单词首字母大写的拷贝
In [22]: print(str1.title())
Hello, World!
# 获得字符串变大写后的拷贝
In [23]: print(str1.upper())
HELLO, WORLD!
# 获得字符串变小写后的拷贝
In [24]: print(str1.lower())
hello, world!
# 从字符串中查找子串所在位置
In [25]: print(str1.find('or'))
8
In [26]: print(str1.find('shit'))
-1
# 从字符串中查找子串所在位置
In [27]: print(str1.index('or'))
8
# 与find类似但找不到子串时会引发异常
In [28]: print(str1.index('shit'))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-14f5d665a183> in <module>
----> 1 print(str1.index('shit'))
ValueError: substring not found
# 检查字符串是否以指定的字符串开头
In [29]: print(str1.startswith('He'))
False
In [30]: print(str1.startswith('hel'))
True
检查字符串是否以指定的字符串结尾
In [31]: print(str1.endswith('!'))
True
# 将字符串以指定的宽度居中并在两侧填充指定的字符
In [32]: print(str1.center(50, '*'))
******************hello, world!*******************
# 将字符串以指定的宽度靠右放置左侧填充指定的字符
In [33]: print(str1.rjust(50, ' '))
hello, world!
# 以下方法是字符串的判断方法
In [34]: str2 = 'abc123456'
# 检查字符串是否由数字构成
In [35]: print(str2.isdigit())
False
# 检查字符串是否由字母构成
In [36]: print(str2.isalpha())
False
# 检查字符串是否以数字和字母构成
In [37]: print(str2.isalnum())
True
In [38]: str3 = ' hello,world '
In [39]: print(str3)
hello,world
# 获得字符串修剪左右两侧空格之后的拷贝
In [40]: print(str3.strip())
hello,world
以上就是python中关于字符串的一些用法,希望对大家有帮助。