Python _ string operations, python _ string operations

Source: Internet
Author: User
Tags string methods

Python _ string operations, python _ string operations
I. String methods and operations

* Note: if the first character is l, it indicates the operation from the left. If the first character is r, it indicates the operation from the right.

1. _ contains _ () determines whether to include

Determines whether a specified character or string is contained in a string. the return value is true or false.

str1="asdfgh"print(str1.__contains__('a'))print(str1.__contains__("df"))print(str1.__contains__('r'))
View Code

 

Running result:

True

True

False

Similar to in

str1="asdf"print('s' in str1)

 

Running result:

True

2. _ eq _ () equal

Determines whether two strings are equal. The return value is True or False.

str1="asdf"print(str1.__eq__("asdf"))print(str1.__eq__("addfd"))

 

Running result:

True

False

3. You can use % s + to add strings.
str1="asd"str2="fgh"str3=str1+str2str4="%s%s"%(str1,str2)print(str3)print(str4)
View Code

 

Running result:

"Asdfgh"

"Asdfgh"

4. format String concatenation
Str1 = "as {0} dsz {1}" result = str1.format ("hu", "ui") print (result) str2 = "as {id} dsfdfz {name}" result = str2.format (id = "hu", name = "ui ") # The variables in the format cannot use print (result) outside)

 

Running result:

"Ashudszui"

"Ashudsfdfzui"

5. Capital of the first letter of the capitalize () String
str1="asdfg"print(str1.capitalize())

 

Running result:

"Asdfg"

6. lowercase letters of casefold ()
str1="ASDFG"print(str1.capitalize())

 

Running result:

"ASDFG"

7. center () center the content with two parameters
# Either a parameter or two parameters, followed by a fill character. The default value is space str1 = "sdfg" print (str1.center (20) print (str1.center (30, '*'))

 

Running result

        sdfg        
*************sdfg*************
8. encode () Encoding
Change the string encoding str1 = "Lan yanru" print (str1.encode ("gbk "))

 

Running result:

B '\ xc0 \ xbc \ xd1 \ xde \ xc8 \ xe3'

9. endswith () determines whether a string ends with a certain character.
str1="asdfdgdghfh"print(str1.endswith('h'))print(str1.endswith('e'))

 

Running result:

True
False
10. expandtabs () converts the tab to space \ t

* Self-thinking is useless

str1="sdfdf\t1ws"print(str1)print(str1.expandtabs())

 

Running result:

sdfdf1ws
sdfdf 1ws
11. find finds the position of a character in the string. If not,-1 is displayed. You can add the start position and end position.
str1="sdgfhfh"print(str1.find('h'))print(str1.find('a'))

 

Running result:

4
-1
12. index return position

Returns the position of the character in the string. If no character is found, an error is returned.

str1="sdgfhfh"print(str1.index('h'))print(str1.index('a'))

 

Running result:

4
Traceback (most recent call last): File "/usercode/file.py", line 8, in print(str1.index('a'))ValueError: substring not found
13. join () is used for splicing. "" represents the separator and can be defined.
str1=['s','o','n','g',]print("".join(str1))print(str1)print("-".join(str1))

 

Running result:

song
['s', 'o', 'n', 'g']
s-o-n-g
14. Put ljust () on the left, same as the center

Like the center, the string is located in a row. ljust is located from the left, and the parameter is the length starting from the left.

str1="qeretry"print(str1.ljust(10,'+'’))print(str1.ljust(20,'-'))print(str1.ljust(30))print(str1.ljust(30,'*'))

 

Running result:

qeretry+++
qeretry-------------
qeretry
qeretry***********************
15. lower () lower case

All lower case

str1="AsdFGd"print(str1.lower())print(str1)

 

Running result:

asdfgd
AsdFGd
16. lstrip () removes spaces on the left
str1="  ddfd  "print(str1.lstrip())

 

Running result:

ddfd  
17. maketrans () and translate () Methods

These two methods need to be compared and used together

str1="12345"str2="asdfg"aa="afgjdfhd"makes=aa.maketrans(str2,str1)print(aa.translate(makes))

 

Running result:

145j34h3

18. partition ("separated characters ")
str1="woaipython"print(str1.partition("ai"))

 

Running result:

('wo', 'ai', 'python')
19. replace () replace name. replace ('old characters', 'new characters ')
Name. replace ('old characters', 'new characters', 'converted several ')
str1="asdfghjkladadafgasag"print(str1.replace('a','p'))print(str1.replace('a','q',3))

 

Running result:

psdfghjklpdpdpfgpspg
qsdfghjklqdqdafgasag
20. rfind ()

The same method as find is used. The difference is that right-to-left search.

21. Just ust ()

The usage is the same as that of ljust. The difference is that right-to-left lookup.

22. rsplit () specifies characters to split strings

The specified character is deleted.

str1="qwetatrassongsdchengxcxu"print(str1.rsplit('s'))

 

Running result:

['qwetatra', '', 'ong', 'dchengxcxu']
23. splitlines () are separated by line breaks, equivalent to split ('\ n ')
str1='''"aa""bb""cc"'''print(str1.splitlines())str1='''"aa""bb""cc"'''print(str1.splitlines())

 

Running result:

['"aa""bb""cc"']
['"aa"', '"bb"', '"cc"']
24. What does startswith () start?

Determines whether a string starts with a character or string.

str1="adgdfgsdf"print(str1.startswith('a'))print(str1.startswith("ad"))print(str1.startswith("ddd"))

 

Running result:

True
True
False
25. swapcase () case-sensitive conversion. The value is smaller and smaller.
str1="dsDDfFDSSSSSFFqqq"print(str1.swapcase())

 

Running result:

DSddFfdsssssffQQQ
26. title () converts a string into a title, that is, an uppercase letter.
str1="dkjgdkgj"print(str1.title())

 

Running result:

Dkjgdkgj
Ii. Summary

1. Common Methods

Center (), startswith (), ljust (), interval ust () ,__ eq _ (), partition (), replace (), rsplit (), splitlines (), lstrip (), rstrip (), strip (), join (), index (), format ()

2. Make sure that you get into the habit of adding a comma (eg: str = ['1', 'A',]) to the element, whether it is a tuples, list, or dictionary.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.