The most important data types in Python include strings, lists, tuples, dictionaries, and so on. This article mainly describes the string basics of Python.
I. String Basics
A string refers to an ordered set of characters, enclosed in single, double, triple (single, double) quotes. such as:
s1= ' www.csdn.net ' s2= ' www.csdn.net ' s3= ' aaabbb '
The string also includes:
1. Escaping a string
Some letters are defined in C as preceded by "\" to denote common ASCII characters that cannot be displayed, and Python also has escape characters. The following:
\\-backslash symbol \ '-Single quotation mark \ '-double quotation mark \ A-Bell \b-backspace (Backspace)
\ n-Wrap \r-carriage return \f-\v-portrait tab \t-transverse tab \e-escape
\000-null \oyy-octal number YY represents the character \xyy-decimal yy represents the character
2.raw String
the original string in Python (raw strings), R closes the escape mechanism. Tell Python that it is followed by a string, "\" improper escape character handling. Example:
#转义字符和raw字符s1 = "AA\NBB" Print S1s2=r "aa\nbb" Print s2# output Aabbaa\nbb#raw raw string processing disk path open (R ' C:\temp\test.txt ', ' A + ') open (' C:\\temp\\test.txt ', ' A + ')
3.unicode String
tells Python that Unicode encoding, Unicode (Uniform Code, Universal Code) is a character encoding used on a computer. ASCII is used before Unicode, Unicode represents a character by using one or more bytes. In Python, all literal strings are ASCII-encoded, and you can declare a Unicode string by prefixing the string with a ' u ', the ' u ' The prefix tells Python the string to be followed by a Unicode string. Example: S=u ' aa\nbb '
Chinese processing has been a headache, recommended: unicode and Python's Chinese processing
4. Format string
string formatting function using the string formatting operator% (percent semicolon), in% To the left of a string (formatted string), and the right side of the value you want to format, but also the tuple and dictionary. If you need to include a percent semicolon in the string, use a percentage. If the right side is a tuple, each of them will be formatted separately, each of which corresponds to a conversion specifier. Example:
"your age%d,sex%s,record%f"% ("Male", 78.5)
output: ' Your age 28,sex male,record 78.500000 '
It's a bit like the C language of printf ("%d", X), where percent percent percent Equivalent to the C language comma. Where the string format conversion type is as follows:
D,i signed Decimal integer
o unsigned octal
U non-signed decimal
x hexadecimal without symbol (lowercase)
X hexadecimal without symbol (uppercase)
E,e scientific notation for floating-point numbers (lowercase, uppercase)
F,f decimal Floating-point number
C Single character
R string (any Python converted using repr)
s string (any Python converted using str)
The G,g index is greater than 4 or less than the precision value and E is the same, otherwise and F is the same
Two. String Manipulation
the underlying operations of strings include segmentation, indexing, multiplication, judging membership, seeking lengths, and so on.
1.+ Connection operation
such as: s1= ' csdn ' s2= ' Eastmount ' s3=s1+s2
Print s1,s2 = output: Csdn eastmount
Print S3 = output: Csdneastmount
2.* Repeat Operations
such as: s1= ' abc '
Print S1 = output: abcabcabcabcabc
3. Index S[index]
Python's index format String_name[index], you can access character members inside a string.
4. sectioning S[i:j]
The basic format for slicing in Python is s[i:j:step], where step represents the direction of the slice, the starting point is not written from 0, and the end is not written to the end. For example:
s= ' Abcdefghijk '
Sub=s[3:8]
Print Sub = = Output Defgh_
3 78 (starting point is 3 end 8 not taken)
where step=-1 is the inverse direction slice. For example:
s= ' Abcdefghijk '
SUB=S[-1:-4:-1]
Print Sub = output Kji
because the last "1" represents a slice from the opposite direction, s[9]= ' J ' s[-2]= ' J ', the positive direction of the first ' a ' index subscript value is 0, and the last ' K ' index subscript value is-1. So ' J ' is-2, and sub[-1:-4:-1] is cut from K ( -1 position) to H ( -4 position, but not the value). So the result is "Kji".
If you want to complete the string in reverse order, s= ' www.baidu.com ', you can s1=[-1::-1]. The starting point is M (-1), and no end point is cut to the last.
5. Field width and precision
The knowledge is involved in the format () function described earlier, such as '%6.2f '%12.345678 output "Port 12.35" where 6 represents the field width, 2 is the precision, so a space is used, and the rounding method results in the output 12.35.
At the same time, 0 (0) can indicate that the number will be filled with 0, minus (-) is used to achieve the left-justified value, white space ("") means that positive numbers are preceded by a space, is very useful when positive negative values, plus indicates whether positive or negative numbers are identified by the symbol, alignment is also useful. Example:
#字段宽度和精度num = 12.345678s1 = '%6.2f '%numprint s1# supplement 0s2 = '%08.2f '%numprint s2# minus to achieve left alignment s3 = '%-8.2f '%numprint s3# blank print ('% 5d '%10) + ' \ n ' + ('% 5d '%-10) #符号print ('%+5d '%10) + ' \ n ' + ('%+5d '%-10) #输出 12.3500012.3512.35 -10 +10 -10
Three. String Methods
Strings "Inherit" a lot of methods from the string module, here are some common methods:
Find ()
finds a substring in a long string that returns the leftmost index at the location of the substring, and returns 1 if none is found. The format is "S.find (sub [, Start [, end]], int", Where the method accepts optional start and end parameters. RFind () looks from right to left.
title = ' Hello python,great Python ' length = len (title) Print Lengthprint title.find (' python ') print title.find (' Python ', 10,30) #输出: 25619
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. " That 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) #连接字符串列表 Sep means ' + ' connection dirs = ', ' usr ', ' bin ', ' env ' print '/'. Join ( dirs) print ' C: ' + ' \ \ '. Join (dirs) #输出1 +2+3+4/usr/bin/envc:\usr\bin\env
Split ()
The string split function, formatted as "S.split ([Sep [, Maxsplit]]), List of strings", divides the string into sequences, and if you do not provide a delimiter, the program will use all the spaces as separators.
#按空格拆分成4个单词, return lists = ' Please use the python! ' Li = S.split () print liprint ' 1+2+3+4+5 '. Split (' + ') #输出 [' Please ', ' use ', ' the ', ' python! '] [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ']
strip ()
S.strip ([chars]) removes the specified character by removing the opening and closing spacebar (on both sides and without the interior). The function Lstrip () Removes all the spaces at the beginning of the string, and Rstrip () strips all the trailing spaces of the string.
replace ()
The method returns all occurrences of a string that are replaced with a string, such as the "Find and replace" feature in a word-processing program.
translate ()
This method, like replace, can replace a part of a string, but the difference is that translate only handles a single character, and its advantage is that it can be replaced at the same time, sometimes more efficient than replace.
such as: s= ' Eastmount ' s1=s.replace (' e ', ' e ') => replace after ' Eastmount '
string-Judging method
isalnum () to determine whether it is a valid character (letter + number), such as the password to determine the account, Output Ture\false.
Isalpha () to determine if it is a letter
isdigit () Determines whether the number
islower () determines whether it is all lowercase
Isupper () determines if all uppercase
isspace () determines whether it is a space (')
lower ()
the method returns the lowercase master of a string, using the. Upper () conversion to uppercase when determining the user name is not case-sensitive, the title () function converts the string to a title-the first letter of all words is capitalized, and the other letter is lowercase, but the word partitioning method it uses may get unnatural results .
PS: I am mainly through the "Basic Python Tutorial" and "51CTO College Zhipu Education python Video" learning. So the article cited a lot of video in the knowledge, book knowledge and their knowledge, thanks to those authors and teachers, hope that the article is helpful to everyone, and began to learn Python knowledge, If there are errors or shortcomings in the article, also please Haihan, also hope that you put forward suggestions and June mutual encouragement. Do not spray ~
(by:eastmount 2014-9-28 Noon 11 o'clock Original CSDN http://blog.csdn.net/eastmount/ )
[Python learning] topic three. Basics of strings