Python字符串
字符串
字符串是 Python 中最常用的数据类型。我们可以使用引号( ’ 或 " )来创建字符串。
name = "Hangzhou"
area = "Gongshu"
history = "5000"
person = """苏轼,许仙,白素贞"""
cap = '''吴越, 南宋'''
-
注意:
单引号和双引号使用时需要注意匹配关系,且不可以换行。如果要换行,使用三单引号或者三双引号。
字符串的运算及常见操作
下表实例变量a值为字符串 “Hello”,b变量值为 “Python”:
操作符 | 描述 | 实例 |
---|---|---|
+ | 字符串连接 | a + b 输出结果: HelloPython |
* | 重复输出字符串 | a*2 输出结果:HelloHello |
[] | 通过索引获取字符串中字符 | a[1] 输出结果 e |
[ : ] | 截取字符串中的一部分,遵循左闭右开原则,str[0,2] 是不包含第 3 个字符的。 | a[1:4] 输出结果 ell |
in | 成员运算符 - 如果字符串中包含给定的字符返回 True | ’H’ in a 输出结果 True |
not in | 成员运算符 - 如果字符串中不包含给定的字符返回 True | ’M’ not in a 输出结果 True |
r/R | 原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母 r(可以大小写)以外,与普通字符串有着几乎完全相同的语法。 | print( r'\n' ) print( R'\n' ) |
a = "Hello"
b = "Python"
print("a + b 输出结果:", a + b)
print("a * 2 输出结果:", a * 2)
print("a[1] 输出结果:", a[1])
print("a[1:4] 输出结果:", a[1:4])
if( "H" in a) :
print("H 在变量 a 中")
else :
print("H 不在变量 a 中")
if( "M" not in a) :
print("M 不在变量 a 中")
else :
print("M 在变量 a 中")
print (r'\n')
print (R'\n')
"""
a + b 输出结果: HelloPython
a * 2 输出结果: HelloHello
a[1] 输出结果: e
a[1:4] 输出结果: ell
H 在变量 a 中
M 不在变量 a 中
"""
sr = "hello python"
print(sr[:5])
print(sr[::-1])
print(sr[::2])
"""
hello
nohtyp olleh
hlopto
"""
Python 的字符串内建函数
字母的大小写
sr = "life is short, you NEED python."
print(sr.lower())# 全部变成小写
print(sr.upper())# 全部变成大写
print(sr.swapcase())# 大小写互换
print(sr.title())# 每个单词的首字母大写
print(sr.capitalize())# 只有字符串的第一个字母的首字母大写,其余都为小写。
"""
life is short, you need python.
LIFE IS SHORT, YOU NEED PYTHON.
LIFE IS SHORT, YOU need PYTHON.
Life Is Short, You Need Python.
Life is short, you need python.
"""
demo:
certid = 'AbCd'
ipt = input("请输入验证码:")
if ipt.lower() == certid.lower():
print("输入成功")
else:
print("输入有误")
字符串的格式输出对齐
center([len], [填充符号]),居中对齐
ljust([len], [填充符号]),居左对齐
rjust([len], [填充符号]),居右对齐
zfill([len]),居右对齐,默认填充0
demo:
print(sr.center(41, '*'))
print(sr.ljust(41, '*'))
print(sr.rjust(41, '*'))
print(sr.zfill(41))
"""
*****life is short, you NEED python.*****
life is short, you NEED python.**********
**********life is short, you NEED python.
0000000000life is short, you NEED python.
"""
删除指定字符
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)或字符序列。
**注意:**该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
sr = "*****life is short, you NEED python.*****"
print(sr.strip("*"))
print(sr.lstrip("*"))
print(sr.rstrip("*"))
"""
life is short, you NEED python.
life is short, you NEED python.*****
*****life is short, you NEED python.
"""
字符串的计数
count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
str.count(sub, start= 0,end=len(string))
-
sub – 搜索的子字符串
-
start – 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
-
end – 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
str="www.runoob.com" sub='o' print ("str.count('o') : ", str.count(sub)) sub='run' print ("str.count('run', 0, 10) : ", str.count(sub,0,10)) """ str.count('o') : 3 str.count('run', 0, 10) : 1 """
字符串搜索定位和替换
-
find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。
str.find(str, beg=0, end=len(string))
- str – 指定检索的字符串
- beg – 开始索引,默认为0。
- end – 结束索引,默认为字符串的长度。
-
index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。
str.index(str, beg=0, end=len(string))
- str – 指定检索的字符串
- beg – 开始索引,默认为0。
- end – 结束索引,默认为字符串的长度。
-
replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
str = "this is string example....wow!!!" print(str.replace("is", "was")) print(str.replace("is", "was", 1)) """ thwas was string example....wow!!! thwas is string example....wow!!! """
字符串的条件判断
Str.isalnum() #是否全是字母和数字,并至少有一个字符
Str.isalpha() #是否全是字母,并至少有一个字符
Str.isdigit() #是否全是数字,并至少有一个字符
Str.isspace() #是否全是空白字符,并至少有一个字符
Str.islower() #S中的字母是否全是小写
Str.isupper() #S中的字母是否便是大写
Str.istitle() #S是否是首字母大写的
sr = "Life Is Short, You Need Python."
print(sr.istitle())
True
制表符的转化
expandtabs() 方法把字符串中的 tab 符号(’\t’)转为空格,tab 符号(’\t’)默认的空格数是 8。
sr = "Life Is Short,\tYou Need Python."
print(sr.expandtabs())
"""
Life Is Short, You Need Python.
"""
sr = "Life Is Short,\tYou Need Python."
print(sr.expandtabs(32))
"""
Life Is Short, You Need Python.
"""
字符串的分割变换
- join(),将指定字符插入元素之间
s1 = "-"
s2 = ""
seq = ("r", "u", "n", "o", "o", "b") # 字符串序列
print (s1.join( seq ))
print (s2.join( seq ))
"""
r-u-n-o-o-b
runoob
"""
-
split(),以指定字符分割字符串并去除该字符
-
partition(),以指定字符分割字符串并保留该字符
sr = "Life Is Short, You Need Python."
print('+'.join(sr))
list1 = ["I ", "LOVE ", "PYTHON "]
print(''.join(list1))
print(sr.split('o'))
print(sr.split('o', 2))
print(sr.partition('o'))
"""
L+i+f+e+ +I+s+ +S+h+o+r+t+,+ +Y+o+u+ +N+e+e+d+ +P+y+t+h+o+n+.
I LOVE PYTHON
['Life Is Sh', 'rt, Y', 'u Need Pyth', 'n.']
['Life Is Sh', 'rt, Y', 'u Need Python.']
('Life Is Sh', 'o', 'rt, You Need Python.')
"""
ASCII值和字符的的转化
chr() 数字转化成字母
ord() 字母转化成数字
for i in range(ord('a'), ord("z") + 1):
print(chr(i), end=' ')
"""
a b c d e f g h i j k l m n o p q r s t u v w x y z
"""
# 拓展:
import string
print(dir(string))
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)
"""
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
"""
for i in range(8):
print(oct(i), end=' ')
print()
for i in range(16):
print(hex(i), end=' ')
"""
0o0 0o1 0o2 0o3 0o4 0o5 0o6 0o7
0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc 0xd 0xe 0xf
"""
print('%o' % 8)# 格式化无符号八进制数
print('%x' % 15)# 格式化无符号十六进制数
"""
10
f
"""