This article mainly introduces the tutorial on the use of str (string) in python3. The introduction in the article is very detailed. The operations of various str strings in python3 are included in this article. Friends who need it can refer to it. , let’s take a look below.
This article mainly introduces a summary of the use of str (string) in python3. The introduction in the article is very detailed. Friends who need it can take a look below.
__add__ function (appends a string at the end)
s1 ='Hello' s2 = s1.__add__(' boy!') print(s2) #输出:Hello boy!
__contains__ (determines whether a string is contained, and returns True if it does)
s1 = 'Hello' result = s1.__contains__('He') print(result) #输出:True
__eq__ (determines two characters Whether the strings are the same, return True if they are the same)
s1 = 'Hello' s2 = 'How' result = s1.__eq__(s2) print(result) #输出:False
__format__
#占位
__getattribute__
#占位
__getitem__
#占位
__getnewargs__
#占位
__ge__ ( Greater than or equal to)
print('b'.__ge__('a')) #输出:True
__gt__(greater than)
print('b'.__ge__('a')) #输出:True
__hash__
#占位
__iter__
#占位
__len__(return string length)
print('abc'.__len__()) #输出:3
__le__ (less than or equal to)
print('b'.__le__('a')) #输出:False
__lt__ (less than)
print('b'.__lt__('a')) #输出:False
__mod__
#占位
__mul__
#占位
__new__
#占位
__ne__
#占位
__repr__
#占位
__rmod__
#占位
__rmul__
#占位
__sizeof__
#占位
__str__(return to self)
print('abc'.__str__()) #输出:abc
capitalize (capitalize the first letter)
s = 'tom' print(s.capitalize()) #输出:Tom
casefold (convert uppercase to lowercase)
s = 'TOM' print(s.casefold()) #输出:tom
center (specify the length and padding characters, the content is centered, and the padding characters are left blank if they are spaces)
s = 'Tom' print(s.center(20,'-')) #输出:--------Tom---------
count (calculate the number of occurrences of a certain string, the second parameter: starting position, the third parameter: ending position)
s = 'aabbbcccccdd' print(s.count('cc',3,11)) #输出:2
encode (encoding)
s = "中文" print(s.encode('gbk')) #输出:b'\xd6\xd0\xce\xc4'
endswith (to determine whether a string ends with a certain character or string, the second parameter: starting position, the third parameter: ending position)
s = 'Projects' print(s.endswith('ts')) print(s.endswith('e',0,5)) #输出:True # True
expandtabs (convert 1 tab key into 7 spaces)
s = 'H\ti' print(s.expandtabs()) #输出:H i
find (find the index position of a character or string, second parameter: starting position, third parameter: ending position)
s = 'Hello' print(s.find('o')) print(s.find('o',0,3)) #找不到返回-1 #输出:4 # -1
format (String formatting/splicing)
name = 'Tom' age = 18 s = '{0}\'s age is {1}'.format(name,age) print(s) #或者 str = '{name}\'s age is {age}' result = str.format(age=18,name='Tom') print(result) #输出:Tom's age is 18
format_map
#占位
index (find the index position of a character or string, which is different from find. If the character does not exist, an error will be reported)
s = 'Hello' print(s.index('o')) print(s.index('e',0,3)) #输出:4 # 1
isalnum(whether it is a letter or number)
s = '!#' print(s.isalnum()) #输出:False
isalpha(whether it is a letter)
s = '123' print(s.isalpha()) #输出:False
isdecimal(whether it is a decimal number)
s = '123' print(s.isdecimal()) #输出:True #True: Unicode数字,,全角数字(双字节) #False: 罗马数字,汉字数字 #Error: byte数字(单字节)
isdigit (whether it is a number)
s = '123' print(s.isdigit()) #输出:True #True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字 #False: 汉字数字
isidentifier (whether it is an identifier/variable name)
s = '1num' print(s.isidentifier()) #输出:False #因为变量名不能以数字开头
islower (whether it is all lowercase letters)
s = 'Hello' print(s.islower()) #输出:False
isnumeric (whether it is a number)
s = '123' print(s.isnumeric()) #输出:True #True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
isprintable (whether it is a printable character/can it be output as is)
s = '\n' print(s.isprintable()) #输出:False
isspace (whether it is a space)
print(' '.isspace()) print('\t'.isspace()) #输出:True # True
istitle (whether it is a title/the beginning of each word Letters in uppercase)
print('Hello Boy'.istitle()) print('hello boy'.istitle()) #输出:True # False
isupper (whether all letters are in uppercase)
print('BOY'.isupper()) print('Boy'.isupper()) #输出:True # False
join (join the elements in the sequence with specified characters to generate a new string)
s = ['H','e','l','l','o'] print(''.join(s)) print('-'.join(s)) #输出:Hello # H-e-l-l-o
ljust (Specify the length and padding characters, the content is left-justified, and the padding characters are left blank if they are spaces)
s = 'Hello' print(s.ljust(10,'-')) #输出:Hello-----
lower (all strings are changed to lowercase)
s = 'TOM' print(s.lower()) #输出:tom
lstrip (remove the string The characters specified on the left, the default is a space)
s = ' Tom' print(s.lstrip()) #输出:Tom
maketrans (Create a conversion table for character mapping, used with the translate function)
intab = "abcde" outtab = "12345" trantab = str.maketrans(intab, outtab) str = "Hello abc" print (str.translate(trantab)) #输出:H5llo 123
partition (Specify the separator to split the string)
s = 'IamTom' print(s.partition('am')) #输出:('I', 'am', 'Tom')
replace (Replace old (old string) in the string with new (new string). If the third parameter max is specified, the replacement will not exceed max times. )
s = 'Tom' print(s.replace('m','o')) #输出:Too
rfind(Find the position where the specified string appears from the right, if there is no match, return -1)
s = 'one two one' print(s.rfind('one')) print(s.rfind('one',0,6)) #指定起始和结束位置 #输出:8 # 0
rindex(Find the position where the specified string appears from the right, if there is no match If there is a match, an error will be reported)
s = 'one two one' print(s.rindex('one')) print(s.rindex('one',0,6)) #指定起始和结束位置 #输出:8 # 0
rjust(Specify the length and padding characters, the content will be right-aligned, and the padding characters will be blank if left blank)
s = 'Hello' print(s.rjust(10,'-')) #输出:-----Hello
rpartition( 指定分隔符,从右边开始将字符串进行分割)
s = 'IamTom_IamTom' print(s.rpartition('am')) #输出:('IamTom_I', 'am', 'Tom')
rsplit(指定分隔符对字符串进行切片,如果指定第二个参数num,则只分隔num次,最后返回一个列表)
s = 'a b c d' print(s.rsplit()) print(s.rsplit(' ',2)) #从右边开始,按空格分隔两次 #输出:['a', 'b', 'c', 'd'] # ['a b', 'c', 'd']
rstrip(删除字符串末尾的指定字符,默认为空格)
s = '!!! I am Tom !!!' print(s.rstrip('!')) #输出:!!! I am Tom
split(指定分隔符对字符串进行切片,如果指定第二个参数num,则只分隔num次,最后返回一个列表)
s = 'a b c d' print(s.split()) print(s.split(' ',2)) #从左边开始,按空格分隔两次 #输出:['a', 'b', 'c', 'd'] # ['a', 'b', 'c d']
splitlines(按换行符来分隔字符串,返回一个列表)
s = 'a\nb\nc' print(s.splitlines()) #默认参数为False print(s.splitlines(True)) #指定Ture参数,则保留换行符 #输出:['a', 'b', 'c'] # ['a\n', 'b\n', 'c']
startswith(判断字符串是否以某个字符或字符串开头的,第二个参数:起始位置,第三个参数:结束位置)
s = 'Projects' print(s.startswith('Pr')) print(s.startswith('e',4,8)) #输出:True # True
strip(删除字符串前后的指定字符,默认为空格)
s = '!!! I am Tom !!!' print(s.strip('!')) #输出: I am Tom
swapcase(大小写互换)
s = 'I am Tom' print(s.swapcase()) #输出:i AM tOM
title(转换成标题,就是每个单词首字母大写)
s = 'i am tom' print(s.title()) #输出:I Am Tom
translate(根据maketrans方法创建的表,进行字符替换)
intab = "abcde" outtab = "12345" trantab = str.maketrans(intab, outtab) str = "Hello abc" print (str.translate(trantab)) #输出:H5llo 123
upper(小写转换成大写)
s = 'Hello' print(s.upper()) #输出:HELLO
zfill(指定字符串的长度。原字符串右对齐,前面填充0)
s = 'Hello' print(s.zfill(10)) # 输出:00000Hello
The above is the detailed content of Detailed explanation of how to use str string in python3. For more information, please follow other related articles on the PHP Chinese website!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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),

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft