The basics of Python strings are detailed

Source: Internet
Author: User
The most important data types in Python include strings, lists, tuples, dictionaries, and so on. This article focuses on Python's string fundamentals. Let's take a look at the little series.

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 S1 s2=r "AA\NBB" Print s2  #输出 aa bb aa\nbb  #raw原始字符串处理磁盘路径 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 always been a headache, recommended: Unicode and Python Chinese processing

4. Formatting strings

The string formatting feature is implemented using the string formatting operator% (percent semicolon), where a string (formatted string) is placed to the left of the%, and the right side places the values you want to format, but also tuples and dictionaries. If you need to include a percent semicolon in the string, use a percentage. If the right side is a tuple, Each of these elements is individually formatted and each value 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 is equal to the C language comma. 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 point 8 not taken)

Where Step=-1 is indicated by the inverse direction of the 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, 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 bit) , but this value is not taken). 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.345678 S1 = '%6.2f '%num print s1 #补充0 s2 = '%08.2f '%num print s2 #减号实现左对齐 s3 = '%-8.2f '%num print S3 #空白 Print ('% 5d '%10) + ' \ n ' + ('% 5d '%-10) #符号 print ('%+5d '%10) + ' \ n ' + ('%+5d '%-10)  #输出  12.35 00012.35 12.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 length print title.find (' python ') print title.find (' Python '), 10,30)  #输出: 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. " 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 ' + ' connect  dirs = ', ' usr ', ' bin ', ' env ' print '/'. Join (d IRS) print ' C: ' + ' \ \ '. Join (dirs)  #输出 1+2+3+4/usr/bin/env C:\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 list s = ' Please use the python! ' li = S.split () Print Li print ' 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 () determines whether all valid characters (Letters + numbers), such as the password account, output ture\false.

Isalpha () to determine if it is a letter

IsDigit () Determine if it is a number

Islower () Determine if all lowercase

Isupper () Determine if all uppercase

Isspace () to determine if 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.

s = ' This was a good idea ' S1 = s.upper () print S1 s2 = s.title () Print S2 #输出 The is a good idea of this was a  good idea

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 ~

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.