首页 > 编程语言 >Python 的字符串内建函数

Python 的字符串内建函数

时间:2023-06-03 17:11:11浏览次数:40  
标签:string Python python 空格 print 内建函数 str 字符串

Python capitalize()方法

将字符串的第一个字母变成大写,其他字母变小写

print("第一个内建函数str.capitalize()")
s1 = 'a,b'
s2 = 'A,B'
s3 = 'a,BCD'
s4 = ' a,B'  #因为a前面有个空格,所以不显示大写
print(s1.capitalize())
print(s2.capitalize())
print(s3.capitalize())
print(s4.capitalize())

#结果
第一个内建函数str.capitalize()
A,b
A,b
A,bcd
 a,b

Python center()方法

返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格。

print("""第二个内建函数str.center(width, [fillchar])
width -- 字符串的总宽度
fillchar -- 填充字符""")
str = "runoob"
print(str.center(20,'*'))
print(str.center(20))
第二个内建函数str.center(width, [fillchar])
width -- 字符串的总宽度
fillchar -- 填充字符
*******runoob*******
       runoob     

Python count()方法

统计字符串里某个字符或子字符串出现的次数

print("第三个内建函数str.count(sub, start= 0,end=len(string))")
str = "this is string example ..... wow!!!"
sub = "i"
print("str.count(sub, 4, 40) : ",end=" ")
print(str.count(sub,2))
第三个内建函数str.count(sub, start= 0,end=len(string))
str.count(sub, 4, 40) :  3

 

Python decode()方法

str.decode(encoding='UTF-8',errors='strict'

以 encoding 指定的编码格式解码字符串。默认编码为字符串编码。

Python encode()方法

以 encoding 指定的编码格式编码字符串

Python endswith()方法

判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False

 

print("""str.endswith(suffix[, start[, end]])
suffix -- 该参数可以是一个字符串或者是一个元素。
start -- 字符串中的开始位置。
end -- 字符中结束位置。
""")
str = "this is string example ... wow!!!"
suffix = "wow!!!"
print(str.endswith(suffix))
print(str.endswith(suffix,20))
suffix = 'is'
print(str.endswith(suffix,2,4))
print(str.endswith(suffix,2,6))
str.endswith(suffix[, start[, end]])
suffix -- 该参数可以是一个字符串或者是一个元素。
start -- 字符串中的开始位置。
end -- 字符中结束位置。

True
True
True
False

  

Python expandtabs()方法

把字符串中的 tab 符号 \t 转为空格,tab 符号 \t 默认的空格数是 8,在第 0、8、16...等处给出制表符位置,如果当前位置到开始位置或上一个制表符位置的字符数不足 8 的倍数则以空格代替。

 

print("str.expandtabs(tabsize=8) tabsize -- 指定转换字符串中的 tab 符号('\t')转为空格的字符数。")
str = "runoob\t12345\tabc"
print("原始字符串:{}".format(str))
# 默认 8 个空格
# runnob 有 6 个字符,后面的 \t 填充 2 个空格
# 12345 有 5 个字符,后面的 \t 填充 3 个空格
print('替换 \\t 符号: {}'.format(str.expandtabs()))
# 2 个空格
# runnob 有 6 个字符,刚好是 2 的 3 倍,后面的 \t 填充 2 个空格
# 12345 有 5 个字符,不是 2 的倍数,后面的 \t 填充 1 个空格
print('使用 2 个空格替换 \\t 符号: {}'.format(str.expandtabs(2)))

# 3 个空格
print('使用 3 个空格: {}'.format(str.expandtabs(3)))

# 4 个空格
print('使用 4 个空格: {}'.format(str.expandtabs(4)))

# 5 个空格
print('使用 5 个空格: {}'.format(str.expandtabs(5)))
str.expandtabs(tabsize=8) tabsize -- 指定转换字符串中的 tab 符号('	')转为空格的字符数。
原始字符串:runoob	12345	abc
替换 \t 符号: runoob  12345   abc
使用 2 个空格替换 \t 符号: runoob  12345 abc
使用 3 个空格: runoob   12345 abc
使用 4 个空格: runoob  12345   abc
使用 5 个空格: runoob    12345     abc

  

Python find()方法

检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

Python format 格式化函数

基本语法是通过 {} 和 : 来代替以前的 % 

print("python format 格式化函数")
print("{} {}".format("hello","world"))
print("{0} {1}".format("hello", "world"))
print("{1} {0} {1}".format("hello","world"))


print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))

# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

class AssingValue(object):
    def __init__(self,value):
        self.value = value
my_value = AssingValue(8)
print("value 为 :{.value}".format(my_value))
python format 格式化函数
hello world
hello world
world hello world
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
网站名:菜鸟教程, 地址 www.runoob.com
value 为 :8

  

Python index()方法

测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常

str1 = "this is string example ... wow!!!"
str2 = "exam"
print(str1.index(str2))
print(str1.index(str2,10))
print(str1.index(str2,40))
15
15
ValueError: substring not found

  

python isalnum()

检测字符串是否由字母和数字组成

python isalpha()

检测字符串是否只由字母组成

python isdecimal()

检测字符串是否只包含十进制字符

python isdigit()

检测字符串是否只由数字组成,只对0和正数有效

python islower()

检测字符串是否由小写字母组成

python isnumber()

检测字符串是否只由数字组成

python isspace()

检测字符串是否只由空格组成

python istitle()

检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写

python isupper()

检测字符串中所有的字母是否都为大写

python join()

将序列中的元素以指定的字符连接生成一个新的字符串

symbol = "-"
seq = ("a","b","c")
print(symbol.join(seq))
a-b-c

python ljust()

返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串

str = " this is string example...wow!!!"
print(str.ljust(40,"0"))
 this is string example...wow!!!00000000

  

python lower()

转换字符串中所有大写字符为小写

python lstrip()

截掉字符串左边的空格或指定字符

返回截掉字符串左边的空格或指定字符后生成的新字符串

str = "    this is string example...wow!!!          "
print(str.lstrip())
str1 = "*****this is string example...wow!!! *** "
print(str1.lstrip('*'))
this is string example...wow!!!          
this is string example...wow!!! ***         

  

python maketrans()

用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。

python max()

返回字符串中最大的字母

pytho min()

返回字符串中最小的字母

python partition()

根据指定的分隔符将字符串进行分割

如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串

str = "www.runoob.com"
print(str.partition("."))
已连接到 pydev 调试器(内部版本号 221.5787.24)('www', '.', 'runoob.com')

  

python replace()

将字符串中的old替换成new,如果指定第三个参数,则替换不超过max次

str = "this is string example...wow!!!this is really string"
print(str.replace("is","was"))
print(str.replace("is","was",3))
thwas was string example...wow!!!thwas was really string
thwas was string example...wow!!!thwas is really string

  

python rfind()

返回字符串最后一次出现的位置,如果没有匹配项则返回 -1

str = "this is really a string example....wow!!!"
substr = "is"

print (str.rfind(substr))
print (str.rfind(substr, 0, 10))
print (str.rfind(substr, 10, 0))

print (str.find(substr))
print (str.find(substr, 0, 10))
print (str.find(substr, 10, 0))
5
5
-1
2
2
-1

  

python rindex()

返回子字符串 str 在字符串中最后出现的位置

str = "this is really a string example....wow!!!"
substr = "is"
print(str.rindex(substr))
print(str.index(substr))
5
2

  

python rjust()

返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。

str = "this is really a string example....wow!!!"
print(str.rjust(50,'0'))
000000000this is really a string example....wow!!!

python rpartition()

该方法是从目标字符串的末尾也就是右边开始搜索分割符

str = "www.runoob.com"
print(str.rpartition("."))
('www.runoob', '.', 'com')

  

python rstrip()

删除 string 字符串末尾的指定字符,默认为空白符,包括空格、换行符、回车符、制表符

str = "this is good    "
print(str.rstrip())
print(str.rstrip("si oo"))
print(str.rstrip('sid oo'))
print(str.rstrip('d oo g s  i'))

website = 'www.runoob.com'
print(website.strip("m/."))
this is good
this is good
this is g
th
www.runoob.co

  

python split()

指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串

str = '1111 \n 2222 \n333333'
print(str.split())
print(str.split(' ',1))
['1111', '2222', '333333']
['1111', '\n 2222 \n333333']

  

python splitlines()

按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。

str1 = 'ax c\n\nde fg\rkl\r\n'
print(str1.splitlines())
print(str1.splitlines(True))
['ax c', '', 'de fg', 'kl']
['ax c\n', '\n', 'de fg\r', 'kl\r\n']

  

python startswith()

检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False

str = 'this is string example...wow!!!'
print(str.startswith("this"))
print(str.startswith("is",2,4))
True
True

python strip()

用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列

str = "     sssssssssss      "
print(str.strip())
str = '1123aaaaaaaaaaaaaaa321'
print(str.strip('12'))
sssssssssss
3aaaaaaaaaaaaaaa3

python swapcase()

将大写字母转换为小写字母,小写字母会转换为大写字母

python title()

所有单词都是以大写开始,其余字母均为小写

str = "this is string example...wow!!!"
print(str.title())
This Is String Example...Wow!!!

python translate()

根据参数table给出的表(包含 256 个字符)转换字符串的字符

python upper()

将字符串中的小写字母转为大写字母

python zfill()

返回指定长度的字符串,原字符串右对齐,前面填充0

str = "this is strign example...wow!!!"
print(str.zfill(40))
000000000this is strign example...wow!!!

  

 

标签:string,Python,python,空格,print,内建函数,str,字符串
From: https://www.cnblogs.com/cimengmenga/p/17447491.html

相关文章

  • 字符串进行切割——split() 方法
    Python的split()方法可以对字符串进行切割,得到一个字符串列表。该方法的语法是:pythonstring.split(sep=None,maxsplit=-1)参数说明:-sep:分隔符,默认是所有的空字符,包括空格、换行(\n)、制表符(\t)等。-maxsplit:切割的次数,默认是-1,代表切割所有的分隔符。例如:......
  • 【python】多线程
     在Python3中,通过threading模块提供线程的功能。原来的thread模块已废弃。但是threading模块中有个Thread类(大写的T,类名),是模块中最主要的线程类,一定要分清楚了,千万不要搞混了。threading模块提供了一些比较实用的方法或者属性,例如:方法与属性描述current_thread()返......
  • python后台执行程序
    Windows系统搭建好Python的环境后,进入Python的安装目录,大家会发现目录中有python.exe和pythonw.exe两个程序。如下图所示:它们到底有什么区别和联系呢?概括说明一下:python.exe在运行程序的时候,会弹出一个黑色的控制台窗口(也叫命令行窗口、DOS/CMD窗口);pythonw.exe是无窗口的Pyth......
  • 用Python开发输入法后台(10)——删除已有词
    有些已经组好的词,可能是不小心组错了,需要删除它,我的输入法暂时还不支持,现在来实现它.用户场景用户正常选词,如下所示:然后按Del键,进入删除模式最后按F1~F9键,删除指定的词......
  • 6-3|Python更新已有的记录
    >>>user.save() #save()returnsthenumberofrowsmodified.>>>user.id>>>user.save()>>>user.id>>>huey.save()>>>huey.id如果你更新多个记录,使用UPDATE插询。下列例子将更新Tweet多个满足如果是昨天之前发表的实例,将它们标示为已发表,Model.upda......
  • 【LeeCode】205. 同构字符串
    【题目描述】给定两个字符串 s 和 t ,判断它们是否是同构的。如果 s 中的字符可以按某种映射关系替换得到 t ,那么这两个字符串是同构的。每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以......
  • Python 读取CSV
    importcsvdefparseCSVFileStr(data):"""将csv转换为[{},{},{},{},{},{},]形式的列表"""titleFlag=0ldata=[]ltitle=[]data=data.replace('"','')forrowindata.spli......
  • 2023.6.2 统计范围内的元音字符串数
    可以用前缀和解。首先建立一个前缀和数组prefix,令n为words的长度,那么prefix的长度就是n+1。(将下标0空出来)然后遍历words中的每一项,如果该项符合规则,则prefix[i]=prefix[i-1]+1,否则prefix[i]=prefix[i-1。(意味着,这个位置有一个字符串可以提供1个贡献)最后遍历querie......
  • 2023-06-03 初试python爬取文章
    注意:本实验是在windows系统下操作。首先配置python环境以及安装一些必要的库:安装python请前往python官网下载,仙人指路......
  • Python time 模块
    常用#float整数位为秒time.time()#struct_timetime.localtime()#stringtime.ctime()#stringtime.asctime()转换#struct_timetime.localtime(float)#floattime.mktime(struct_time)#struct_timetime.strptime(string,"%Y-%m-%d%H:%M:%S")#......