Python topic basic knowledge of three strings, python Basics

Source: Internet
Author: User
Tags iterable

Python topic basic knowledge of three strings, python Basics

The most important data types in Python include strings, lists, tuples, and dictionaries. This article describes the basics of Python strings.

I. String Basics

A string refers to an ordered character sequence set, which is enclosed by single quotation marks, double quotation marks, and triple quotation marks (single or double quotation marks). For example:

S1 = 'www. csdn. net' s2 = "www. csdn. NET" s3 = '''aaabbb '''

The strings include:

1. Escape string

For example, the C language defines some ASCII characters that cannot be displayed by adding "\" to the front of the letters, and python also has escape characters:

\-Backslash symbol \ '-single quotation marks \ "-double quotation marks \ a-bell \ B-Backspace)

\ N-line feed \ r-press enter \ f-form feed \ v-vertical tab \ t-horizontal tab \ e-escape

\ 000-null \ oyy-octal yy represents the character \ xyy-decimal yy represents the character

2. raw string

In Python, the original string (raw strings), r closes the escape mechanism, and tells Python that it is followed by escape, "\" improper Escape Character Processing. For example:

# Escape Character and raw character s1 = "aa \ nbb" print s1 s2 = r "aa \ nbb" print s2 # output aa bb aa \ nbb # raw string processing disk path open (r'c: \ temp \ test.txt ', 'a +') open ('C: \ temp \ test.txt ', 'a + ')

3. unicode string

It tells Python to use Unicode encoding. Unicode (Uniform Code, universal code) is a character encoding used on computers. unicode uses ASCII code before Unicode. Unicode uses one or more bytes to represent a character. by default, all literal strings in Python are encoded in ASCII format. You can declare a Unicode string by adding a 'u' prefix to the string, the 'U' prefix tells the strings after Python to be compiled into Unicode strings. example: s = u'aa \ nbb'

Chinese processing has always been a headache. Recommended: Unicode and Python Chinese Processing

4. format the string

The string Formatting Function is implemented using the string formatting operator % (percent). Put a string (formatted string) on the left side of %, and put the value to be formatted on the right side, but also the tuples and dictionaries. to include the percent sign in the string, use %. if the right is a tuple, each element is formatted separately, and each value corresponds to a conversion specifier. example:

"your age %d,sex %s,record %f"%(28,"Male",78.5)

Output: 'ur age 28, sex Male, record 100'

It is somewhat similar to the C-language printf ("% d", x). The percent sign % is equivalent to a comma in the C language. The string format conversion type is as follows:

D, I-Signed decimal integer

O unsigned octal

U unsigned decimal

X non-Signed hexadecimal (lower case)

X unsigned hexadecimal (uppercase)

Floating point numbers represented by e, E scientific notation (lower case, upper case)

F, F decimal floating point number

C Single Character

R string (any Python converted using repr)

S string (any Python converted using str)

G, G index greater than 4 or less than the same precision value and e, otherwise it is the same as f

Ii. String operations

Basic operations on strings include segmentation, indexing, multiplication, determining membership, and length determination.

1. + connection operations

For example, s1 = 'csdn 's2 = 'astmount' s3 = s1 + s2

Print s1, s2 => output: csdn Eastmount
Print s3 => output: csdnEastmount

2. * repeated operations

Example: s1 = 'abc' * 5

Print s1 => output: abcabcabcabcabc

3. index s [index]

The index format of Python is string_name [index]. You can access character members in the string.

4. Slice s [I: j]

In Python, the basic format of slice is s [I: j: step]. step indicates the direction of the slice. the start point is not written from 0, and the end point is not written to the end. For example:

S = 'abcdefghjk 'sub = s [] print sub => output defgh _ 3 78 (the start point is 3 and the end point is 8)

When step =-1, the slice is in the opposite direction. For example:

S = 'abcdefghjk 'sub = s [-1:-4:-1] print sub => output kji

Because the last "-1" indicates the slice from the opposite direction, s [9] = 'js' [-2] = 'J ', the value of the First 'A' index in the square direction is 0, and the value of the last 'K' index is-1. therefore, 'J' is-2, while sub [-1:-4:-1] indicates to switch from k (-1) to h (-4, but do not take this value ). the result is "kji ".

If you want to reverse the string, s = 'www .baidu.com ', you can use s1 = [-1:-1. the start point is m (-1). If there is no end point, it indicates that it is switched to the end.

5. Field width and precision

This knowledge is involved in the format () function described earlier. For example, '% 6.2f' % 12.345678 output "port 12.35", where 6 indicates the field width and 2 indicates the accuracy. Therefore, a space is added, at the same time, the result is output 12.35 by rounding the result.

At the same time, zero (0) can indicate that the number will be filled with 0, minus signs (-) are used to achieve the left-aligned value, blank ("") means adding a space before a positive number, A positive or negative number is very useful for the time being. A plus sign indicates that symbols are identified no matter whether the positive or negative number is used, and alignment is also useful. example:

# Field width and precision num = 12.345678 s1 = '% 6.2f' % num print s1 # Add 0 s2 = '% 08.2f' % num print s2 # minus sign to achieve left-aligned s3 = '% -8.2f '% num print s3 # blank print (' % 5d '% 10) + '\ n' + (' % 5d '%-10) # print (' % + 5d '% 10) + '\ n' + (' % + 5d '%-10) # output 12.35 00012.35 12.35 10-10 + 10-10

Iii. String Method

Strings are inherited from the string module. The following describes some common methods:

Find ()

Search for a substring in a long string. It returns the leftmost index of the substring's position. If not found,-1 is returned. the format is "S. find (sub [, start [, end])-> int ", where this method accepts optional start and end points. rfind () Searches from right to left.

Title = 'Hello Python, Great python' length = len (title) print length print title. find ('python') print title. find ('python', 10, 30) # output: 25 6 19

Join ()

The format is "S. join (iterable)-> string ", meaning" Return a string which is the concatenation of the strings in the iterable. the separator between elements is S. "is used to add elements to the queue, but the elements in the queue must be strings. it is the inverse method of the split method.

Seq = ['1', '2', '3', '4'] sep = '+ 'print sep. join (seq) # join string list sep indicates '+' connect dirs = '', 'usr', 'bin', 'env' print '/'. join (dirs) print 'C: '+ '\\'. join (dirs) # output 1 + 2 + 3 + 4/usr/bin/env C: \ usr \ bin \ env

Split ()

String segmentation function in the format of "S. split ([sep [, maxsplit])-> list of strings ", splits the string into a sequence. If no Delimiter is provided, the program uses all spaces as separators.

# Split it into 4 words by space and return list s = 'Please use the Python! 'Li = s. split () print li print '1 + 2 + 3 + 4 + 5 '. split ('+') # output ['please', 'use', ''the, 'python! '] ['1', '2', '3', '4', '5']

Strip ()

Remove the Space key at the beginning and end (both sides do not contain the internal), S. strip ([chars]) can remove specified characters. the lstrip () function removes all spaces at the beginning of the string, and rstrip () removes all spaces at the end of the string.

Replace ()

This method returns the string after all the matching items of a string are replaced, for example, the "search and replace" function in the Text Processing Program.

Translate ()

Similar to replace, this method can replace a part of a string. However, the difference between the method and replace is that translate only processes a single character. Its advantage is that it can replace multiple characters at the same time, and sometimes it is more efficient than replace.

For example, s = 'astmount' s1 = s. replace ('E', 'E') => after replacement, 'astmount'

String Judgment Method

Isalnum () determines whether it is a valid character (letter + number), such as determining the password account, Output True \ False.

Isalpha () determines whether it is a letter

Isdigit () determines whether it is a number

Islower () determines whether all data is in lower case

Isupper () determines whether all data is in uppercase

Isspace () determines whether it is a space ('')

Lower ()

This method returns a string in lower case, which is used when determining that the user name is not case sensitive. the upper () function converts a string to a title. The title () function converts a string to a title. The first letter of all words is uppercase, And the other letters are lowercase, however, the word division method it uses may produce unnatural results.

S = 'this is a good idea 's1 = s. upper () print s1 s2 = s. title () print s2 # output this is a good idea this Is A Good Idea

PS: I mainly learned through "Python basics" and "python video of zhipu education at 51CTO College. therefore, the article cited a lot of knowledge in the video, books and their own knowledge. Thanks to the authors and teachers, I hope the article will help you to learn python knowledge, if there are any errors or deficiencies in the article, please ask Hai Han and I hope you will share your comments with me. do not spray ~

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.