Python Learning Notes--string method

Source: Internet
Author: User

Center: Used to pad characters on both sides to center the string
' The middle is Sssssss '. Center (20)
' The middle is LX '

Strip: Delete beginning and end whitespace characters
' The middle is LX '. Strip ()
' The middle is LX '
names=[' lx ', ' dt ', ' xx '

>> name= ' LX '
>> if name in Names:print (' This is true ')
...
>> if Name.strip () in Names:print (' This is true ')
...
This is true

Find: Finds a substring in a string, returns the index of the first occurrence of a substring
' The middle is LX '. Find (' lx ')
14

Join: Merging string sequence elements
seq=[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']

>> sep.join (seq)
' 1+2+3+4+5 '

Split: Splitting a sequence of strings
Seq= ' 1+2+3+4+5+6 '

>> seq (). Split (' + ')
Traceback (most recent):
File "<stdin>", line 1, in <module>
TypeError: ' str ' object is not callable
>> seq.split (' + ')
[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ']
>> sep=seq.split (' + ')
>> Sep
[' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ']

Lower: return string lowercase version

' TTT111 '. Lower ()
' ttt111 '

Replace: Replaces the specified string with another string. and returns the result after the substitution
This is a test '. Replace (' was ', ' is ')
' Thare is a test '

>> ' This was a test '. Replace (' is ', ' ere ')
' There ere a test '

Translate: Replacing a specific part of a string, only single-character substitution
To pre-set the conversion table, you can use Str.maketrans (' cs ', ' KZ ') This, Maketrans accept two parameters, two length of the same string, specifying the previous string is replaced by a string, you can set the third parameter is to delete the specified character, such as a space
Table=str.maketrans (' CS ', ' KZ ', ')

>> ' Ffccctttsss sssssss '. Translate (table)
' Ffkkktttzzz zzzzzzz '
>> ' Ffccctttsss sssssss '. Translate (table)
' Ffkkktttzzz zzzzzzz '
>> Table=str.maketrans (' cs ', ' KZ ', ')
>> ' Ffccctttsss sssssss '. Translate (table)
' Ffkkktttzzzzzzzzzz '

Python Learning Notes--string method

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.