1. 字符串的连接
方式1:使用加号 +
s1 =“Hello”
s2 =" World"
s = s1 + s2
print(s) # 输出 “Hello World”
方式2:使用占位符 %s
整型变量使用%d
print(“Hello %s”%“World”) # 输出相同的字符串
2. 字符串中的转义符 \
print(“What\'s your name?”)
输出:What’s your name?
也可是在双引号中使用单引号
print(“What’s your name?”) 输出的结果是一样的
还有一个特殊的用法在语句最后表示续行符
lines =“This is line 1”\
“Line2”\
“Line3”
print(lines) # 输出:This is line 1Line2Line3
3. 字符串的复制
方式1,使用星号 ,和算数运算中的乘法一样
s =“test”
print(s *3) #输出: testtesttest
s2 = s
print(s2) # 输出:test
4. 字符串长度计算
使用len() 函数
s =“This is a test string”
print(len(s)) # 21
5. 字符串转换
s =“test ok”
print(s.upper()) # 转大写
print(s.lower()) # 转小写
print(s.capitalize()) # 句子首字母大写
print(s.istitle()) # 是否首字母大写
print(s.isupper()) #是否全部大写
print(s.islower()) # 是否全部小写
6. 字符串切片,索引取值
这个是最常见的,也是最重要的
s[startIndex: endIndex] 切片索引的起始地址
s =“How old are you?”
print(s[0])# 索引取值,第一个字母H
print(s[-1])# ?
print(s[4:7])# old
print(s[4:])# old are you?
print(s[:7])# How old
print(s[:])# 全部字符串
7. 去掉字符串两端的空格
s =" Hello World "
print(len(s))
print(s)
print(s.strip()) # 除掉左右2边的空格
print(s.lstrip()) # 除掉左边空格
print(s.rstrip()) # 除掉右边空个
8.字符串分隔
与列表可相互转换,因为分隔后返回的是字符串列表
s =“This is a test string”
print(s.split())# 默认空格分隔
print(s.split(‘s’))# 按照字符’s’分隔
# 列表转字符串
mylist =[“one”, “two”, “three”]
s ="_".join(mylist)
print(s) # one_two_three
可使用空格,下划线等任意字符串将列表元素连成一个字符串
9. 字符串格式化
# 字符串格式化
print(s.center(20, “*”)) # 格式字符串长度,不够使用* 填充
10. 判断字符串的开头和结尾
s =“Test OK”
print(s.startswith(“Te”))
print(s.endswith(“OK”))
print(s.startswith(“OY”))
11.其它非常实用的函数
str( ) 函数:将其它类型转为字符串类型
print(“I am " +str(100)+” years old") # 将整型数字转换为字符串类型
上面演示了绝大多数的字符串方法和属性,不是全部的,下面介绍一个函数,可以查看所有的字符串方法和属性:
dir( )函数
print(dir(str))
输出:[’__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmod__’, ‘__rmul__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘capitalize’, ‘casefold’, ‘center’, ‘count’, ‘encode’, ‘endswith’, ‘expandtabs’, ‘find’, ‘format’, ‘format_map’, ‘index’, ‘isalnum’, ‘isalpha’, ‘isascii’, ‘isdecimal’, ‘isdigit’, ‘isidentifier’, ‘islower’, ‘isnumeric’, ‘isprintable’, ‘isspace’, ‘istitle’, ‘isupper’, ‘join’, ‘ljust’, ‘lower’, ‘lstrip’, ‘maketrans’, ‘partition’, ‘removeprefix’, ‘removesuffix’, ‘replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rpartition’, ‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’, ‘title’, ‘translate’, ‘upper’, ‘zfill’]
我不一一测试验证和演示,但是还有一个函数能帮你学习每一个方法,不需要任何老师,那就是help( )函数,
例如:print(help(str.isalnum))
输入:
Help on method_descriptor:
isalnum(self, /)
Return True if the string is an alpha-numeric string, False otherwise.
A string is alpha-numeric if all characters in the string are alpha-numeric and
there is at least one character in the string.
None
Python字符串的知识基本讲解完成,如果哪里有问题,或者讲解错误,可以联系我。
如果能帮助到你,请给我鼓励。