本篇文章主要介绍字符串的各种方法和案例,感兴趣的朋友参考下,希望对大家有所帮助。
代码如下:
'''字符串:是以单引号或双引号括起来的任意文本, ‘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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment