Python Base---string

Source: Internet
Author: User
Tags printable characters

strings (String)

Definition: a series of characters;

In Python, a string is enclosed in "or";

is one of the most commonly used data types in Python (datatype).

Common operations:

1. Connection operation [+]:

x = str1 + str2

1 var1 = ' 123 ' 2 var2 = ' 456 ' 3 Var3 = var1 + var24 print (VAR3) 5--->123456

2. Copy operation [*]:

x = str1 * n n must be an integer.

1 var1 = ' 123 ' 2 VAR4 = var1 * Print (VAR4) 4--->123123123

3. Index operation [[]]:

x = Str[n] n is the position of x in the string, and in Python, the count starts at 0.

1 var1 = ' abcde0 ' 2 var2 = var1[0]3 print (VAR2) 4--->a

4. Slicing operation [[::]]:

x = str[a:b: c] A is the starting position, B is the terminating position (in the result, does not contain a B value), and C is the value of the index increment (default is 1).

1 var1 = ' abcde0 ' 2 var2 = var1[0:3]3 print (VAR2) 4--->abc5 6 var1 = ' abcdefghijklmnopqrstuvwxyz ' 7 var2 = var1[0:15:2]8 Print (VAR2) 9--->acegikmo

5, member check [in & Not in]:

Checks if x is in the string and returns a bool value;

' x ' in str ' x ' isn't in str

1 var1 = ' ABCDEFG ' 2 print (' A ' in var1) 3 print (' A ' isn't in var1) 4--->true5--->false

6. Original string [R & R]:

All strings are used directly in the literal sense, without escaping special or non-printable characters.

The original string has almost exactly the same syntax as a normal string, except that the first quotation mark of the string is preceded by the letter "R" (which can be case).

R "Str"

1 var1 = R ' a\nb\\c\ ' d\ "EFG ' 2 print (VAR1) 3--->a\nb\\c\ ' d\" EFG

Escape character in string: Python uses a backslash (\) to escape characters when special characters are used in characters.

1. Continuation: \ Use at end of line

1 var1 = ' ABCDE2         FG '

2, backslash symbol: \ \ in the output string display a \

1 var1 = ' ABCDE\\FG ' 2 print (VAR1) 3--->ABCDE\FG

3, single & double quotes: \ ' & \ ' displays a ' or ' in the output string

1 var1 = ' abc\ ' de\ ' FG ' 2 print (VAR1) 3--->abc "DE ' FG

4, Empty: \000 displays a space in the output string

1 var1 = ' ABCDE\000FG ' 2 print (VAR1) 3--->abcde FG

5. NewLine: \ nthe string is output as two lines

6, Landscape & Portrait tab: \ T & \v

1 var1 = ' \TABCDEFG ' 2 print (VAR1) 3--->    ABCDEFG

string-related common functions:

1, Capitalize (): Capitalize the first character of the string

1 var1 = ' Hello_world ' 2 print (Var1.capitalize ()) 3--->hello_world

2, Title (): Returns the "caption" of the string, that is, all the words are started in uppercase, the remaining letters are lowercase

1 var1 = ' Hello_world ' 2 print (Var1.title ()) 3--->hello_world

3, Upper () & Lower (): Capitalize all characters & lowercase

1 var1 = ' Hello_world ' 2 print (Var1.upper ()) 3 4 var2 = ' ABCDEFG ' 5 print (Var2.lower ()) 6 7--->hello_world8--->ABCDEFG

4, Swapcase (): Uppercase and lowercase in a string

1 var2 = ' ABcdeFG ' 2 print (Var2.swapcase ()) 3--->ABCDEFG

5. Len (): Gets the string length

1 var1 = ' Hello_world ' 2 print (len (var1)) 3--->11

6, COUNT (): Number of occurrences of the specified character in the statistics string

Count (' x ', A, c) ' x ' is the specified character; A, B is the range of start and end intervals (the interval does not contain b. The default is to find all intervals)

1 var = ' Abcdergaaaawerwasfwwweaatse ' 2 print (Var.count (' A ')) 3--->84 print (var.count (' A ', 0,)) 5--->5

7, find () & Index (): Finds the position of the first occurrence of the specified character in the string

Find (): Returns the index of the specified character in the string if it is found, or 1 if it does not exist

Index (): Usage same as find (), but if not present, error

1 var1 = ' Hello_world ' 2 print (Var1.find (' L ')) 3--->2 4 print (Var1.find (' G ')) 5--->-1 6 print (Var1.index (' l ')) 7- -->2 8 Print (Var1.index (' G ')) 9--->traceback (most recent call last):   "file path", line 5, in <module>1 1     Print (Var1.index (' G ')) valueerror:substring not found

8. Split (): use a specific character to cut a string into a list of multiple strings

Str. Split(str="", num=string. Count(str)) parameter num is the number of splits

1 var1 = ' Hello_world_hello_china ' 2 print (Var1.split ('_')) 3--->[' hello ', ' world ', ' hello ', ' China ']4 print ( Var1.split (' _ ', 1)) 5--->[' hello ', ' World_hello_china ']

9, Splitlines (): Separated by line (' \ r ', ' \ r \ n ', \ n '), returns a list containing the rows as elements

Str. Splitlines([keepends]) keepends whether to remove newline characters (' \ r ', ' \ r \ n ', \ n ') in the output, default to False, does not contain newline characters, and if true, line breaks are preserved

1 var1 = ' A\NBCD\REF\R\NGHIJ\RKLMN ' 2 print (Var1.splitlines ()) 3--->[' a ', ' BCD ', ' ef ', ' ghij ', ' KLMN ']4 print ( Var1.splitlines (True)) 5--->[' a\n ', ' bcd\r ', ' ef\r\n ', ' ghij\r ', ' KLMN ']

10. Join (): Generates a new string (equivalent to split's reverse operation) of the elements in the sequence with the specified character connection

  Str. Join(sequence) sequence is the sequence of elements to concatenate

1 List1 = [' A ', ' B ', ' C ', ' d ', ' e ']2 var1 = '-'. Join (LIST1) 3 print (VAR1) 4--->a-b-c-d-e

11, Strip (chars) |--both sides--|

Lstrip (chars) removes the--|--start--|--symbol of the string, strips the space by default, and spaces the specified symbol after it is removed.

Rstrip (chars) |--End--|

Chars for the specified character

1 var1 = '  abcd  ' 2 var2 = ' @@[email protected]@ ' 3 print (Var1.strip ()) 4--->ABCD 5 print (Var1.lstrip ()) 6--- >ABCD   7 print (Var1.rstrip ()) 8--->  ABCD 9 print (Var1.strip (' @ ')) Ten--->  ABCD  

12, Zfill (): 0 of the fill effect (commonly used for data storage in the database)

Center (width, fillchar) |--Center

Ljust (width, Fillchar) fills the string with the specified character, the original string content--|--left

Rjust (width, fillchar) |--right

Width is the total length of the new string, Fillchar is the character to be filled in

*warning*:

    1. The default is a space if the Fillchar parameter is not supplied
    2. When the width parameter is less than or equal to the length of the original string, returns
    3. The right character will be 1 less than the left when you cannot make equal numbers
1 var1 = ' ABCD ' 2 print (Var1.zfill) 3--->000000abcd4 print (var1.center (9, ' ¥ ')) 5--->¥¥¥abcd¥¥6 print ( Var1.ljust (9, ' ¥ ')) 7--->abcd¥¥¥¥¥8 print (var1.rjust (9, ' ¥ ')) 9--->¥¥¥¥¥ABCD

13, Maketrans () and Translate (): string substitution operation

Str. Maketrans(intab, outtab, Deletechars) Intab-a string of characters to be substituted in the string

Outtab--a string of corresponding mapped characters

Deletechars--List of characters to be removed in the string

Str. Translate(table) Table-translation table, translation table is converted by Maketrans method

1 var1 = ' abcdabefffffffff ' 2 var2 = '. Maketrans (' AB ', ' hello ', ' F ') 3 Var3 = Var1.translate (var2) 4 print (VAR3) 5---> Hello cd hello E

14, the detection of strings:

1, starswith (suffix, start, end): Detects whether a string begins with a specified character suffix as a string or an element, start, End to retrieve the starting and ending positions of a string, returning a bool value

EndsWith (suffix, start, end): End of-----------------------------

1 var1 = ' ABCABDCSIDJSFFWAIDDDDKSF ' 2 print (var1.startswith (' AB ')) 3--->true4 print (var1.endswith (' DDD ')) 5---> False

2, Isalnum (): Returns True if the string has at least one character and all characters are letters or numbers, otherwise False

Isalpha (): returns Trueif the string has at least one character and all characters are letters, otherwise False

1 var1 = ' ABCABDCSIDJSFFWAIDDDDKSF ' 2 var2 = ' 22323 ' 3 print (Var1.isalnum ()) 4--->true5 print (Var2.isalpha ()) 6---> False

3, IsDigit (): Returns True if the string contains only a number, otherwise returns FALSE.

Isnumric (): Returns True if the string contains only numeric characters, otherwise False

Isdecimal (): Checks whether the string contains only decimal characters. This method exists only in Unicode objects.

Note: to define a decimal string, simply add the ' u ' prefix before the string.

The following boldface content is referenced from this site Manage blog: http://www.cnblogs.com/jebeljebel/p/4006433.html,

Thank you very much for the results of our predecessors!

isdigit ()
true:unicode number, byte digit (single byte), full-width digit (double byte), Roman numerals
False: Chinese numerals
Error: None

Isdecimal ()
true:unicode number, full-width digit (double-byte)
False: Roman numerals, Chinese numerals
error:byte number (single byte)

IsNumeric ()
true:unicode numbers, full-width numerals (double-byte), Roman numerals, Chinese numerals
False: None
error:byte number (single byte)

  

  

Python Base---string

Related Article

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.