Python lists and strings

Source: Internet
Author: User
Tags string methods uppercase letter

 # divide list, add list ImportNumPy as NPA=[1,2]#1, get list <class ' list ' >B=[i/2 forIinchA];Print(b)#2, get <class ' Numpy.ndarray ' >B=np.array (a)/2;Print(b) # Add and subtract multiple lists, with NumPy C=np.array (a) +np.array (b) * * *Print(c)

#不同长度数据放到一起, with NumPy and pandas are not very good handling
#用list则比较好处理
A=[]
A.append ([up])
A.append ([2,3,4,5,5])
Pd. DataFrame (a)

#判断元素个数
#发行pandas和numpy都不好处理
[1,2,3,1,2, ' A ', ' B ', ' A '].count (' a ') gets the number of ' a ' occurrences

#求两个list差集, intersection, and set http://www.jb51.net/article/56980.htm
A = [n/a]; b = [2,3,4] #想要的结果是 [1] [4] [2,3] [1,2,3,4]
Aa=[i for I in a if I is not in B] #[1]
Bb=[i for i in B if I is not in a] #[4]
Cc=[i for I in a if I in B] #[2,3]
A.extend (b); A[-1:-1]=b; A[0:0]=b; A[1:1]=b #可以插到不同位置, then go heavy

#简单的list去重

a=[1,2,3,2,4,3,1]

A=list (Set (a)) #set (a): {1,2,3,4} a:[1,2,3,4] #python the list pass-through to trace the index of the element being processed

My_list=[' A ', ' B ', ' C ']
For Idx,val in Enumerate (my_list):
Print (Idx,val)
#可以再结合Series. Index[idx] To get the index name, use Loc[series.index[idx],columns_name] to select the specified position value

#替换 Replace
' ABCD '. Replace (' A ', ' x ') #将 ' a ' replaced by ' x ' result ' XBCD '

#合并拼接字符串

Parts=[' is ', ' Chicago ', ' Not ', ' Chicago? '
'. Join (Parts)
', ', Join (parts)
'. Join (Parts)

#字符串截取
String.Split (' key ') #string在key地方截为两段

#用index () method to find values in a list
spam=[' Hello ', ' Hi ', ' Howdy ', ' Heyas ']
Spam.index (' Hello ') #0

#append () Insert () remove () is a list method
#注意得到新的list就是append和insert后的 without assigning a value
#列表被当场修改
Spam.append (' Moose ')
Spam.insert (1, ' chicken ')
Spam.remove (' hello ') #如果该值出现多次, only the first occurrence of the value will be deleted

#sort () sort the values in the list
Sort () method sorting a list on the spot cannot sort a list with both numeric and string values
The sort () method uses "ASCII character order" instead of the actual word when sorting strings
Code order. This means that capital letters are preceded by lowercase letters. So when sorting, the lowercase A is in uppercase.
after Z. If you need to sort in a normal dictionary order, the keyword argument is used when the sort () method is called
The key is set to str.lower.
Spam.sort (reverse=true)
Spam=[' A ', ' Z ', ' a ', ' Z ']
Spam.sort (Key=str.lower) #[' A ', ' a ', ' z ', ' z ']

#如果元组中只有一个值, you can follow a comma after the value in parentheses to indicate that this
Case Otherwise, Python will assume that you just entered a value in a normal parenthesis. Comma tells
Python, which is a tuple (unlike other programming languages that Python accepts after the last table item in a list or tuple
Comma with the face). In the interactive environment, enter the following type () function calls to see how they differ:
>>> type (' Hello ',)
<class ' tuple ' >
>>> type (' Hello ')
<class ' str ' >

#用 the list () and tuple () functions to convert the type

A variable contains a reference to a list value, not the list value itself. But for strings and integer values, the variables
Contains a string or integer value. When a variable must hold a value of a mutable data type, such as a list or dictionary,
PythonThe reference is used. For values of immutable data types, such as strings, integers, or tuples,Python
Variable to save the value itself.
>>> spam = 42
>>> cheese = spam
>>> spam = 100
>>> spam
100
>>> Cheese
the>>>Spam = [0, 1, 2, 3, 4, 5]
>>>Cheese = spam
>>>Cheese[1] = ' hello! '
>>>Spam
[0, ' hello! ', 2, 3, 4, 5]
>>>Cheese
[0, ' hello! ', 2, 3, 4, 5]
Python provides a module named copy , which contains the copy () and deepcopy () functions
If the list you want to copy contains a list, use the copy.deepcopy () function instead.
>>> Import Copy
>>> spam = [' A ', ' B ', ' C ', ' D ']
>>> cheese = copy.copy (spam)
>>> cheese[1] = 42
>>> spam
[' A ', ' B ', ' C ', ' D ']
>>> Cheese
[' A ', ' a ', ' C ', ' D ']
#元组不可修改是元组中的元素不可修改, a tuple variable can be assigned a value modification
temp= (' A ', ' B ', ' C ', ' d ')
temp=temp[:2]+ (' e ',) +temp[2:] # (' A ', ' B ', ' e ', ' C ', ' d ')
2.1, table 6-1 escape characters

The escape character is printed as
\ ' Single quotation mark
\ "Double quotation marks
\ t tab
\ n line break
\ \ Inverted Slash

2.2. String methods Upper (), lower (), Isupper (), and Islower ()

Upper () All caps, lower () all lowercase, isupper () islower () if the string has at least one letter, and all letters are uppercase or lowercase, the isupper () and Islower () methods return the Boolean value True accordingly. Otherwise, the method returns False.

In addition to Islower () and Isupper (), there are several string methods whose names begin with IS. These
Method returns a Boolean value that describes the character of the string. Here are some common IsX string methods:
? Isalpha () returns True if the string contains only letters and is not empty;
? Isalnum () returns True if the string contains only letters and numbers, and is not empty;
? Isdecimal () returns True if the string contains only numeric characters and is not empty;
? Isspace () returns True if the string contains only spaces, tabs, and line breaks, and is not empty;
? ? Istitle () returns True if the string contains only words that begin with an uppercase letter and that are followed by lowercase letters.

Note that these methods do not change the string itself, but instead return a new string. If you want to change
To change the original string, you must call upper () or lower () on the string, and the new string
Assign to the variable that holds the original string. This is why it is necessary to use spam = Spam.upper () in order to change
Spam in the string, instead of just using Spam.upper ()

3. String method StartsWith () and EndsWith ()

This is useful if you only need to check that the start or end of a string is equal to another string, rather than the entire string, which can replace the equals operator = =.

4. String method join () and split ()

The join () method is useful if you have a list of strings that need to be concatenated to become a separate string. The join () method is called on a string, and the argument is a list of strings that returns a
String. The returned string is concatenated by each string in the passed-in list.
The split () method does exactly the opposite: it returns a list of strings for a string call.
', '. Join ([' Cats ', ' rats ', ' bats ')
' Cats, rats, bats '
' My name is Simon '. Split ()
[' My ', ' name ', ' is ', ' Simon ']

A common split () usage is to split multi-line strings according to line breaks. Enter in an interactive environment
The following code:
>>> spam = "Dear Alice,
How are you been? I am fine.
There is a container in the fridge
That is labeled "Milk experiment".
Please don't drink it.
Sincerely,
Bob "
>>> spam.split (' \ n ')
[' Dear Alice, ', ' How are you been? I am fine. ', ' There is a container in the
Fridge ', ' That's ' labeled ' Milk experiment '. ', ', ' please don't drink it. ',
' Sincerely, ', ' Bob '

5. Align the Rjust (), Ljust (), and Center () methods

>>> ' Hello '. Rjust (10)
' Hello '
>>> ' Hello '. Rjust (20)
' Hello '
>>> ' Hello World '. Rjust (20)
' Hello World '
>>> ' Hello '. Center (20, ' = ')
' =======hello======== '

6. Remove whitespace characters with strip (), Rstrip (), and Lstrip ()

>>> spam = ' Hello world '
>>> Spam.strip ()
' Hello World '
>>> Spam.lstrip ()
' Hello World '
>>> Spam.rstrip ()
' Hello World '

Python lists and strings

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.