本篇文章主要介绍字符串的各种方法和案例,感兴趣的朋友参考下,希望对大家有所帮助。
代码如下:
'''字符串:是以单引号或双引号括起来的任意文本, ‘abc’"def" 字符串不可变 ''' #创建字符串 str1 = "sunck is a good man!" str2 = "sunck is a nice man!" #字符串运算 #字符串连接,字符串不可变 str3 = "sunck" str4 = "is a man" str5 = str3 + str4 print(str5) #输出重复字符串 str6 = "hello" str7 = str6 * 3 print(str7) #访问字符串中的某一个字符 #通过索引下标查找字符,从0开始 字符串名[下标] str8 = "sunck is a nice man!" print(str8[1]) #截取字符串,包含前面的6,不包含15[6,15), str9 = "sunck is a nice man!" str10 = str9[6:15] str11 = str9[:6]#从头截取 str12 = str9[16:]#从给定下标处截取到最后 print(str10) #判断有没有需要的字符 str13 = "sunck is a nice man!" print("good" in str13)#false print("good" not in str13)#true #格式化输出 num = 10 print("num = %d" % (num))#%d占位符, num替换%d,%d表示整数 str14 = "sunck is a nice man!" f = 3.14 print("str14 = %s\nf = %.3f" % (str14,f)) #字符串替换用%s代替,浮点用%f表示(%.3f 精确到小数点后三位,会四舍五入) #\n换行 #转义字符 ''' \:将一些字符转换成有特殊含义的字符 \\:表示一个“\” \t:制表符(四个空格) r:如果字符串里有好多字符串都需要转义,允许用r表示内部的字符串默认不转义 ''' print("hello \\ world") print('hello \'world\'') print("hello 'world'") #如果字符串内有很多换行,用\n不好阅读 print(''' hello world ''')#三引号可以换行 print("hello\tworld") #打印\\\t\\ print(r"\\\t\\") #eval() ''' 功能:将字符串str当成有效的表达式来求值,并返回计算结果 ''' num1 = eval("123")#转为整数 print(eval("1+23"))#自动计算,字母不可计算 #len(str) ''' 返回字符串的长度 ''' print(len("hello world"))#长度看字符个数 #str.lower ''' 转换字符串中的大写字母为小写字母 ''' str15 = "suncK is a good man" print(str15.lower()) #str.upper() 转换字符串中的小写字母为大写字母 str16 = "suncK is a good man" print(str16.upper()) #str.swapcase 转换字符串中大写字母为小写字母,小写字母为大写字母。 print("suncK is a good man".swapcase()) #str.capitalize() 首字母大写 print("suncK is a good man".capitalize()) #str.title() 每个单词的首字母大写 print("suncK is a good man".title()) #center(width[,fillchar]) #返回一个指定宽度的居中字符串,fillchar为填充的字符串(默认空格填充) print("suncK is a good man".center(40,"*")) #ljust(width[,fillchar]) #返回一个指定宽度的左对齐字符串,fillchar为填充的字符串(默认空格填充) print("suncK is a good man".ljust(40),"%") #rjust(width[,fillchar]) #返回一个指定宽度的右对齐字符串,fillchar为填充的字符串(默认空格填充) print("suncK is a good man".rjust(40),"%") #zfill(width) #返回一个长度为width的字符串,原字符串右对齐,前面补0。 print("suncK is a good man".zfill(40)) #count(str[,start][,end]) #返回str字符串中str的出现的次数,可以指定一个范围,默认全部 print("suncK is a good good man".count("good",15,len("suncK is a good good man"))) #find(str[,start][,end]) #从左到右,检测str字符串是否包含在字符串中,可以指定范围,默认从头到尾, #返回的是第一次开始的下标,没有返回-1 print("suncK is a good good man".find("good")) print("suncK is a good good man".find("good",15,len("suncK is a good good man"))) #rfind(str[,start][,end]) #从右向左检测 print("suncK is a good good man".rfind("good")) #index(str,start = 0,end = len(str)) #跟find方法基本一样,如果str不存在会报异常 print("suncK is a good good man".index("good")) #rindex(str,start = 0,end = len(str)) #与rfind方法一样,当不存在时会报异常 print("suncK is a good good man".rindex("good")) #lstrip() #截掉字符串左侧指定字符,默认空格 print("*suncK is a good good man".lstrip("*")) #rstrip() #截掉字符串右边的字符,默认空格 print("*suncK is a good good man*".rstrip("*")) #strip() #截掉两边的指定内容,默认空格 print("**suncK is a good good man**".strip("*")) str17 = "a" print(ord(str17)) #输出ASCII值 #字符串比较大小 #从第一个字符开始比较,谁的ASCII的值大就大,如果相等 #就比较下一个字符,谁的值大谁就大 print("mszzz" < "ms") # \0 ASCII:0 #split(str = "",num) 以str为分隔符截取字符串,指定num,则仅截取num个字符 str18 = "sunck is good man" list1 = str18.split(" ") #print(str18.split(" ",3)) c = 0 for s in list1: if len(s) > 0: c += 1 print(c) #splitlines(keepends) 按照(\r, \r\n, \n)分割,返回一个作为 #keepends == True 会保留换行符,默认false(不保留换行符) str19 = ''' sunck is a good man! sunck is a nice man! ''' print(str19.splitlines(True))#true带着换行符输出 #join() 以一个特定的字符串分隔符,将seq中的所有元素组合成一个字符串 list2 = ['sunck','is','a','good','man'] str20 = " ".join(list2) print(str20) #max() min() str21 = "sunck is a good man z" print(max(str21)) print(min(str21)) #replace(oldstr,newstr,count) # 用newstr替换oldstr,默认全部替换,如果制定了count,那只替换count个 str22 = "sunck is a good man" str23 = str22.replace("good","nice",1)#good要替换的单词,nice替换成,1替换第几个 print(str23) #maketrans() 创建字符串的映射表 ''' oldstr要转换的字符串 newstr要转换的字符串 ''' t24 = str.maketrans("sunck","kaige") #将s对应成k,以此类推 str25 = "sunck is a good man" str26 = str25.translate(t24) print(str26) #startswith(str,start = 0,end = len(str)) #判断是否以str开头 str27 = "sunck is a good man " print(str27.startswith("sunck",5,16)) #endswith(str,start = 0,end = len(str)) #在给定的范围内判断是否已给定的字符串开头,如果没有指定范围,默认整个字符串 str28 = "sunck is a good man " print(str28.endswith("man")) #encode(encoding="utf-8",errors="strict") #编码 #str29 = "sunck is a good man" str29 = "sunck凯 is a good man" data30 = str29.encode("utf-8","ignore") #ignore 忽略错误 print(data30) #解码 注意:要与编码时的编码格式一致 str31 = data30.decode("utf-8") print(str31) #isalpha() 如果字符串中至少一个字符且所有的字符都是字母返回True #f否则为false str32 = "sunck is a good man" print(str32.isalpha()) #isalnum() #如果字符串中至少有一个字符且所有的字符都是字母或数字返回true #否则返回false str33 = "123" print(str33.isalnum()) #isupper() #如果字符串中至少有一个英文字符且所有的字符都是大写的英文字母返回true,否则返回false print("ABC".isupper())#返回True print("ABC1".isupper())#返回True print("1".isupper())#返回false print("acn".isupper())#返回false print("ABC#".isupper())#返回true #islower() #如果字符串中至少有一个英文字符且所有的字符都是小写的英文字母返回true print("abc".isupper())#返回True print("abc1".isupper())#返回True print("1".isupper())#返回false print("ABC".isupper())#返回false print("abc#".isupper())#返回true #istitle() #如果字符串是标题化的返回True,否则返回false print("sunck is".istitle())#返回false print("Sunck Is".istitle())#返回True #isdigit() #如果字符串只包含数字字符,返回true,否则返回false print("123".isdigit())#返回true print("123a".isdigit())#返回false #isnumeric() #如果字符串只包含数字字符,返回true,否则返回false print("123".isdigit())#返回true print("123a".isdigit())#返回false #isdecimal() ##如果字符串只包含10进制字符,返回true,否则返回false print("123".isdigit())#返回true print("123a".isdigit())#返回false # #如果字符中只包含空格返回True,否则返回false print(" ".isspace()) print("\t".isspace())#True print("\n".isspace())#true print("\r".isspace())#true
总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。
相关推荐:
The above is the detailed content of Various methods and cases of strings. For more information, please follow other related articles on the PHP Chinese website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor
