python--string

Source: Internet
Author: User

The string type is a very important type in Python and is usually expressed in the form of a character in the middle of a quotation mark, unlike in other languages, where the double quotation marks ("") in Python are not distinguished from single quotation marks (""). Can be used to represent a string

Create, assign, and access 1. Two ways of creating

(1) Direct assignment

s = "abcdef"

(2) by str() function

The function of STR () is equivalent to generating a string object by passing in parameters, which may be integer, float, or list, tuple, dictionary, etc.

str(21"21"str(12.3"12.3"str([123"[1, 2, 3]"

It is important to note that "what is passed in, what is obtained" for example, if we pass a list in, the first character of the resulting string is not the first element of the list, but "[" the same is considered , part of the string.

2. Accessing strings

(1) Accessing a single character

"1234567"print(s[1# "2"print(s[-1# "7"print(s[-7# "1"

strings, of course, are also sequences, so that each element (i.e. each of these characters) corresponds to an index, and the design of the index is the same as in other languages, starting with 0.

In addition, Python also provides a "negative index", that is, the index of the last element is-1, the second-penultimate element is indexed to-2, and so on, the first element of the index is-n (where n is the length of the sequence)

(2) Accessing slices

"1234567"print(s[1:4# "234"

Slicing is a very distinctive syntax in Python, and of course, the object of a slice application is a sequence (string, list, tuple) that he can use to represent a part of the sequence very conveniently. The slice has 3 parameter controls, and his form can be expressed as follows:

[beginendstep]

The middle is : separated, which begin represents the starting position of the sequence to be obtained, and it contains the position, which end means the end position of the sequence is to be obtained, but it cannot contain elements of this position. For example:

s = "1234567"s1 = s[2:5] # >>> 取的是s中第2个位置开始,一直到第4个位置的数,也就是"345"

If we do not explicitly give the corresponding arguments for begin and end, then begin will default to 0,end, which will default to n (sequence length), for example:

s = "1234567"s1 = s[:5] # >>> s1 = "12345"s2 = s[2:] # >>> s2 = "34567"s3 = s[:] # >>> 复制了整个s

The last parameter of the slice, step, means "step", for example:

s = "1234567"s1 = s[1:6:2] # >>> 从第1个位置开始,直到第5个位置结束,每次“跳”2步,得到"246"

It can be understood that, after each element is taken, the steps to "jump" backwards are step, such as the above example is a 2-step jump. But the step parameter is not necessarily given, he defaults to 1, and when the default value of 1 o'clock is used, the one before step : can be omitted without special requirements.

(3) Negative sectioning

There is a special way to use the slice, that is, "negative slices", in layman's terms, is to make step a negative number of slices, since we have said that Python provides "negative index", then according to the same principle, the negative slice is naturally from the beginning, each forward to jump the corresponding steps, such as:

"1234567"print(s[6:1:-1# >>> 依次取6,5,4,3,2位置的元素, 结果是"76543"print(s[-2:-4:-1# >>> 依次取-2,-3位置的元素,结果是"65"

Whether it is a positive slice, or a negative slice, begin and end both meet the "left closed right open" principle. It's just that the slices are from left to right (or back), and negative slices are in the opposite direction.

In the same vein as the positive slice, if

Non-denaturing

As I said before, these types of data are immutable, such as Integer, String, and so on (see my blog: python– memory management), which means that once memory is allocated for these types of data, it cannot be changed. For example, doing the following will throw an exception:

s = "1234567"s[0] = "e"

However, in reality, there are many situations where we need to change the contents of the string itself. So, in Python, our common practice is to re-establish a string object, such as:

s = "1234567"s = s[0:3] + "Python" # >>> s = "123Python"

Although it looks like the result is changing s, it just re-establishes a new string made up of the previous S slice S[0:3] and the string "Python", and is referenced by the name S.

Similarly, we can of course delete some elements of a string in this way, such as:

s = "1234567"s = s[0:3] + s[4:] # >>> s = "123567" 删除了4

As a matter of fact, a new object of type string is created.

The operator of the string 1. Members

We use the in operator not in to judge a character, or whether a string is in another string.

"abcdef"print("ef"in# >>> Trueprint("ac"in# >>> Falseprint("d"notin# >>> False
2. Connect

With a + connection that represents two strings, we have already seen such an example before.

"I wrote""Python"" "# "I wrote Python"
3. Repeat
"123"3# "123123123"

*The meaning of the expression is actually the same as in mathematics, many add up.

4. Compare

The comparison between strings is based on the size of the ASCII code that corresponds to the first different character between two strings.

"abcde""abce"print# >>> False

And when two strings are in front of each other, they are larger with longer strings

"abcd""abc"print# >>> True
The built-in function of the string 1. String length

len(str)to find the length of a string in the form of a

print(len("1234567"# >>> 7
2. Maximum minimum value of the string

In fact, the maximum minimum character of the corresponding ASCII encoding

print(max("abcd""d"print(min("1234""1"
3. Enumerate and zip

Passing strings as arguments enumerate() and zip() functions, generating corresponding enumerate objects and zip-type objects, and then we are going through the loop to output these objects according to our needs. Like what:

Enum_obj = Enumerate ("ABCD"# >>> Create a new object of type enumerate forIndex, EleinchEnum_obj:Print(Index, ele) # >>> output sequentially:1 "a",2 "B",3 "C",4 "D" forIinchZip"ABCD","1234"):Print(i) # >>> output: ("a","1"), ("B","2"), ("C","3"), ("D","4")

Such a function can provide us with a more convenient way to process the data.

4. String Lookup

In addition to the previously mentioned member operators can determine whether a string is in another string, functions find() and index() can do similar work.

"Python"print(s.find("Py"# >>> 0print(s.find("hy"# >>> -1

find()function is the function that if found, then return to the first position of the matching part, if not found, then return-1, of course, the find() function can also set the start and end position of the search. However, the string built-in function is too many, many functions of the parameters are very fine, so I just "to", do not list.

index()The function implements a similar function, but throws an exception if it is not found. Therefore, it is best to use index() a function with the member operator in advance to add a judgment statement, if inside, and then index() return to match the starting position of the field.

s"Python"print(s.index("yth"# >>> 1print(s.index("hy"# >>> 引发异常
5. String discrimination

Python also provides a number of discriminant functions for strings.

(1) Returns string.isalnum() true if the characters in the string are letters or numbers, otherwise false

"123asd""as, 123"print# >>> Trueprint# >>> False

(2) string.isalpha() all characters in string are letters, return true, otherwise false

"Python""C++"print# >>> Trueprint# >>> False

(3) string.isdigit() all characters in string are numeric, return true, otherwise false

"0106584376""010-7487345"print# >>> Trueprint# >>> False

(4)string.isupper()All letters in string are uppercase, return true, otherwise false
&NBSP,   Span class= "Mtext" id= "mathjax-span-5" style= "font-family:stixgeneral-regular;" >&NBSP,   Span class= "Mtext" id= "mathjax-span-7" style= "font-family:stixgeneral-regular;" >  string.islower()All letters in string are lowercase, return true, otherwise false

"SELECT""Python3.5"print# >>> Trueprint# >>> False
6. String substitution

string.replace()function implementation string substitution

"123456"s.replace("456""abc"# "123abc"

The basic parameters are two, old in front, new in the rear

7. String segmentation

There are three commonly used split correlation functions:string.split(); string.partition(); string.join()

(1) string.split() :

"I love you"s.split(" "# >>> 以空格为分隔符,将字符串s分割成一个列表:["I""love""you"]

It is important to note that this method of segmentation is actually the beginning of the string as a point, the end of a point, and then each delimiter is a point, if the next two points between the string, then the string is an element of the list, if there is nothing between adjacent two points, then return a null character (not a space, is a null character "" ) , like the example above, let's change it:

"I  love you  "s.split(" "# >>> 以空格为分隔符,将字符串s分割成一个列表:["I""""love""you"""""]

In fact, we use points to indicate that there is s = ".I..love.you..." a point between the beginning and the end, and that each of the two adjacent points constitutes an element of the list, and we get the result above.

(2) string.partition() :

"I love you"s.partition(" "# >>> 以空格为分隔符,从分隔符出现的第一个位置起,将字符串s分割成一个三个元素的列表:["I"" ""love you"]

partition()function and split() similar, except that the result must be a list of three elements, and the delimiter must be the second element

(3) string.join() :
This is actually a connection function, but I'm still putting it in the split. The function is to concatenate strings in parentheses (note that it must be a sequence of strings, such as a list of strings, etc.) to form a new string, using a string delimiter.

print(",".join(["I""wrote""Python"# >>> "I,wrote,Python"print("**".join("123"# >>> "1**2**3"
8. Case conversion

This article mainly introduces three functions:

(1) string.upper() : Converts all lowercase characters to uppercase, but it is important to note that this only creates a new object and the original object has not changed

"bupt"# "BUPT"# "bupt"

(2) string.lower() : In the same string.upper() vein, only uppercase is converted to lowercase

"Python3"# "python3"

(3) string.swapcase() : Uppercase to lowercase, lowercase to uppercase

"I Need You"# "i nEED yOU"
9. String simplification

Sometimes, you will encounter a string of the leftmost and the right side of the case, and these spaces will affect our processing of strings, so, if there is a function to simplify the string, remove these two paragraphs of space, it will make us very convenient. string.strip()the function is to do this thing.

"   I  Need You     "# "I  Need You"

Note that the spaces in the middle of the string are not affected

Of course, in addition to the 9 aspects I described above, in fact, Python has a lot of built-in functions about strings. Of course, the common basic is here, the other first not introduced. We need to use the time, their own Baidu, there will be relevant answers.

python--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.