https://www.programiz.com/python-programming/string
Python不支持字符类型,它们被视为长度为1的字符串,也被视为子字符串
通过在引号中放置一系列字符来创建字符串。字符串可以用单引号,双引号或三引号括起来,它们由三个单引号或三个双引号组成
三引号中的字符串可以跨越多行而不使用转义字符
默认情况下,Python 2中的字符串是非Unicode(ASCII),但也支持Unicode。
另一方面,Python 3字符串都是Unicode(UTF-8)
Strings in Python 2.
>>> print(type('Python String')) <type 'str'> >>> print(type(u'Python Unicode String')) <type 'unicode'>
Strings in Python 3.
>>> print(type('Python String')) <class 'str'> >>> print(type(u'Python Unicode String')) <class 'str'>
Python中的字符串运算符
字符串索引
查看字母x在字符串中的索引位置
string.index('x')
字符串切片Slicing [ ] Range Slicing [X:y]
使用方括号与索引或索引范围一起切片以获得子串
string = "python"
print(string[4])
slice运算符在给定索引处打印字符
print(string[4])
slice运算符在给定索引处打印字符
print(string[2:4])
打印给定范围内的字符
print(string[::-1])
打印给定范围内的字符
print(string[::-1])
字符串串联Concatenation (+)
string1+string2
将两个字符串合并为一个
字符串重复Repetition (*)
string*9
通过重复给定次数来创建新字符串,它实质上是一个多重串联
>>> ".-." * 4
'.-..-..-..-.'
使用此运算符,我们可以遍历字符串的所有字符成员资格Membership( in,not in)
检查字符串中是否存在某些字符,返回true,false
string="Long"
print("Lo" in string)
#True
print("Ln" in string)
#False
print("Ln" not in string)
#False
迭代Iterating (For)
迭代Iterating (For)
# example for var in var1:print (var, end ="")原始字符串Raw String (r/R)
# example print (r'\n') # \n print (R'\n') # \n
Python中的内置字符串函数
字符串替换 replace(old,new[,count])
var='This is a good example'
str='was'
print (var.replace('is',str))
# Thwas was a good example
print (var.replace('is',str,1))
# Thwas is a good example
string.replace('旧','新')oldstring = 'I like You!'
newstring = oldstring.replace('like', 'love')
print(newstring)
字符串大写
string.upper()
var = 'TechBeamers' print (var.upper()) # TECHBEAMERS
字符串小写
string.lower()
var = 'TechBeamers' print (var.lower()) # techbeamers
字符串首字母大写
string.capitalize()
返回首个单词大写字母,其余小写字母的字符串
var = 'welcome to Python programming' print (var.capitalize()) # Welcome to python programming
string.title()
所有单词均以大写字母开头,单词中的其余字符均以小写字母开头
var = 'welcome to Python programming' print (var.title()) # Welcome To Python Programming
字符串大小写互换
string.swapcase()
var = 'TechBeamers' print (var.swapcase()) # tECHbEAMERS
字符串计数count( str[, beg [, end]])
如果给出了beg和end索引,则返回子字符串'str'在[beg,end]范围内出现的次数,否则搜索将以完整字符串继续进行,字符串搜索区分大小写
var='TechBeamers'
str='e'
print (var.count(str))
# 3
var1='Eagle Eyes'
print (var1.count('e'))
# 2
var2='Eagle Eyes'
print (var2.count('E',0,5))
# 1
rjust(width[,fillchar])
返回String的填充版本,其中原始String左对齐到width列的总和 默认情况下,填充使用空格。否则,“ fillchar”指定填充字符。
ljust(width[,fillchar])返回String的填充版本,其中原始String左对齐到width列的总和 默认情况下,填充使用空格。否则,“ fillchar”指定填充字符
center(width[,fillchar])在将原始内容推入中心的同时返回填充有输入字符的字符串。 默认情况下,填充使用空格。否则,“ fillchar”指定填充字符。
zfill(width)返回填充有原始内容的字符串,该内容在左侧用零填充,以使String的总长度等于输入大小
如果字符串中存在前导符号(+/-),则使用此功能将在符号之后而不是符号之前开始填充
find(str [,i [,j]])在完整的字符串中搜索"str''。如果找到"str'',则此函数返回索引,否则返回"-1''
i = search从此索引开始,j = search从此索引结束
count(str[,i [,j]])返回字符串中子字符串“ str”的出现次数
i = search从此索引开始,j = search从此索引结束
返回String的填充版本,其中原始String左对齐到width列的总和 默认情况下,填充使用空格。否则,“ fillchar”指定填充字符。
var='Python' print (var.rjust(10)) # Python print (var.rjust(10,'-')) # ----Python
ljust(width[,fillchar])返回String的填充版本,其中原始String左对齐到width列的总和 默认情况下,填充使用空格。否则,“ fillchar”指定填充字符
var='Python' print (var.ljust(10)) # Python print (var.ljust(10,'-')) # Python----
center(width[,fillchar])在将原始内容推入中心的同时返回填充有输入字符的字符串。 默认情况下,填充使用空格。否则,“ fillchar”指定填充字符。
var='Python' print (var.center(20)) # Python print (var.center(20,'*')) # *******Python*******
zfill(width)返回填充有原始内容的字符串,该内容在左侧用零填充,以使String的总长度等于输入大小
如果字符串中存在前导符号(+/-),则使用此功能将在符号之后而不是符号之前开始填充
var='Python' print (var.zfill(10)) # 0000Python var='+Python' print (var.zfill(10)) # +000Python
i = search从此索引开始,j = search从此索引结束
var="Tech Beamers" str="Beam" print (var.find(str)) # 5 var="Tech Beamers" str="Beam" print (var.find(str,4)) # 5 var="Tech Beamers" str="Beam" print (var.find(str,7)) # -1index(str[,i [,j]])与“find”方法相同。唯一的区别是,如果不存在“ str”,它将引发“ ValueError”异常
var='Tech Beamers' str='Beam' print (var.index(str)) # 5 var='Tech Beamers' str='Beam' print (var.index(str,4)) # 5 var='Tech Beamers' str='Beam' print (var.index(str,7)) # ValueError: substring not foundrfind(str[,i [,j]])这与find()相同,只是此函数返回找到“str”的最后一个索引。如果未找到“str”,则返回“-1”
var='This is a good example' str='is' print (var.rfind(str,0,10)) # 5 print (var.rfind(str,10)) # -1
count(str[,i [,j]])返回字符串中子字符串“ str”的出现次数
i = search从此索引开始,j = search从此索引结束
var='This is a good example' str='is' print (var.count(str)) # 2 print (var.count(str,4,10)) # 1
反转字符串
string="123456"
string[::-1]
或者"".join(reversed(string))
拆分字符串split([sep[,maxsplit]])
返回用“ sep”作为分隔符分割字符串后获得的子字符串列表
其中sep =分隔符,默认为空格,maxsplit =要进行的分割数
word.split(" ")
分隔符是空格,则返回['I', 'love', 'You!']
word.split("o")
分隔符是o,怎返回['I l', 've Y', 'u!']
join(seq)
返回在将序列“ seq”与定界符字符串连接后获得的字符串。
splitlines(num)
在换行符处拆分字符串,并在删除换行符后返回列表
其中,num =如果这是一个正值。它指示换行符将出现在返回的列表中
从字符串开头删除字符后,返回一个字符串,默认为空格字符
rstrip([chars])
从字符串末尾删除字符后,返回一个字符串
其中:Chars =这是要从字符串中修剪的字符。默认为空格字符
rindex(str[,i [,j]])
在完整的字符串(如果未定义i和j)或字符串的子字符串(如果已定义i和j)中搜索“ str”。此函数返回提供“ str”的最后一个索引
如果“ str”不存在,则会引发ValueError异常, 其中:i 此索引开始,j 索引结束
len(string)
返回给定String的长度
>>> print("%(lang)s is fun!" % {"lang":"Python"})
string="123456"
string[::-1]
或者"".join(reversed(string))
拆分字符串split([sep[,maxsplit]])
返回用“ sep”作为分隔符分割字符串后获得的子字符串列表
其中sep =分隔符,默认为空格,maxsplit =要进行的分割数
var = "This is a good example"
print (var.split())
# ['This', 'is', 'a', 'good', 'example']
print (var.split(' ', 3))
# ['This', 'is', 'a', 'good example']
word = "I love You!"word.split(" ")
分隔符是空格,则返回['I', 'love', 'You!']
word.split("o")
分隔符是o,怎返回['I l', 've Y', 'u!']
join(seq)
返回在将序列“ seq”与定界符字符串连接后获得的字符串。
seq=('ab','bc','cd') str='=' print (str.join(seq)) # ab=bc=cd
splitlines(num)
在换行符处拆分字符串,并在删除换行符后返回列表
其中,num =如果这是一个正值。它指示换行符将出现在返回的列表中
var='Print new line\nNextline\n\nMove again to new line'
print (var.splitlines())
# ['Print new line', 'Nextline', '', 'Move again to new line']
print (var.splitlines(1))
# ['Print new line\n', 'Nextline\n', '\n', 'Move again to new line']
lstrip([chars])从字符串开头删除字符后,返回一个字符串,默认为空格字符
var=' This is a good example ' print (var.lstrip()) # This is a good example var='*****This is a good example*****' print (var.lstrip('*')) # This is a good example**********
rstrip([chars])
从字符串末尾删除字符后,返回一个字符串
其中:Chars =这是要从字符串中修剪的字符。默认为空格字符
var=' This is a good example ' print (var.rstrip()) # This is a good example var='*****This is a good example*****' print (var.lstrip('*')) # *****This is a good example
rindex(str[,i [,j]])
在完整的字符串(如果未定义i和j)或字符串的子字符串(如果已定义i和j)中搜索“ str”。此函数返回提供“ str”的最后一个索引
如果“ str”不存在,则会引发ValueError异常, 其中:i 此索引开始,j 索引结束
var='This is a good example' str='is' print (var.rindex(str,0,10)) # 5 print (var.rindex(str,10)) # ValueError: substring not found
len(string)
返回给定String的长度
var='This is a good example' print (len(var)) # 22
>>> print("%(lang)s is fun!" % {"lang":"Python"})
Python is fun!
>>> "Python is as simple as {0}, {1}, {2}".format("a", "b", "c")
>>> "Python is as simple as {0}, {1}, {2}".format("a", "b", "c")
'Python is as simple as a, b, c'
>>> "Python is as simple as {1}, {0}, {2}".format("a", "b", "c")
'Python is as simple as b, a, c'
>>> xy = {"x":0, "y":10}
>>> print("Graph a point at where x={x} and y={y}".format(**xy))
Graph a point at where x=0 and y=10
format()
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)
# order using positional argument
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)
# order using keyword argument
keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)
>>> # formatting integers
>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'
>>> # formatting floats
>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'
>>> # round off
>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'
# out 3.142
pi = 3.141592653589793
n = 3
print(f"%.{n}f" % pi)
print("{0:.{1}f}".format(pi, n))
print(f"{pi:.{n}f}")
>>> # string alignment 左对齐<,右对齐>或^将字符串居中
>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')
'|butter | bread | ham|'
f'Python {expr}'
format()
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)
# order using positional argument
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)
# order using keyword argument
keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)
>>> # formatting integers
>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'
>>> # formatting floats
>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'
>>> # round off
>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'
# out 3.142
pi = 3.141592653589793
n = 3
print(f"%.{n}f" % pi)
print("{0:.{1}f}".format(pi, n))
print(f"{pi:.{n}f}")
>>> # string alignment 左对齐<,右对齐>或^将字符串居中
>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')
'|butter | bread | ham|'
f'Python {expr}'
expr可以是常量,表达式,字符串或数字或Python对象等形式的任何东西
version = 3.6
feature = 'f-string'
str_final = f'Python {feature} was introduced in version {version}.'
print(str_final)
# Python f-string was introduced in version 3.6.
from datetime import datetime print(f'Date as F-string:\n{datetime.now()}') print(fr'Date as raw string:\n{datetime.now()}')
lambda_test = f"{(lambda x: x * 25) (5)}"
print(lambda_test)
# 125
lambda_test = f"{{999}}"
print(lambda_test)
# {999}
lambda_test = f"{{{999}}}"
print(lambda_test)
# {999}
评论
发表评论