Examples Python3 (VI)

Python is determined whether the presence of the string substring

Given a string, and determines whether the designated character string is present in the sub-string change.

Examples

def check(string, sub_str):
if (string.find(sub_str) == -1):
print("不存在!")
else:
print("存在!")

= String "www.runoob.com"
sub_str = "runoob"
Check (String, sub_str)
implementation of the above code is output is:

presence!
Analyzing Python string length

Given a string, then the string is determined to change the length.

Example 1: Method using the built-len ()

= STR "runoob"
Print (len (STR))
execute the above code output is:

6
Example 2: using a loop calculation

def findLen(str):
counter = 0
while str[counter:]:
counter += 1
returncounter

= STR "runoob"
Print (Findlen (STR))
or more execution code output is:

6
Python using regular expressions to extract string URL

Given a string, which contains the URL, we need to use regular expressions to get the URL string.

Examples

import re

def Find(string):

findall () string to find a matching regular expression

url = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', string)
return url 

string = 'Runoob web address is: HTTPS: //www.runoob.com,Google web address: https://www.google.com '
Print ( "Urls:", the Find (String))
or more execution code The output is:

Urls: [ ' https://www.runoob.com ', ' https://www.google.com ']
the Python code execution strings as

Given a string code, then exec () to execute the code string.

Example 1: Method using the built-len ()

def exec_code():
LOC = """
def factorial(num):
fact=1
for i in range(1,num+1):
fact = fact*i
return fact
print(factorial(5))
"""
exec(LOC)

exec_code ()
or more execution code output is:

120
the Python string flipping

Given a string, which is then inverted, reverse output.

Example 1: using the string sections

= STR 'Runoob'
Print (STR [:: -. 1])
execute the above code output is:

boonuR
Example 2: Use the reversed ()

= STR 'Runoob'
Print (. '' the Join ((STR)) the reversed)
above execution code output is:

boonuR
Python string sections and flip

Given a string that specifies the number of strings taken from the head or tail, which is then inverted stitching.

Examples

def rotate(input,d):

Lfirst = input[0 : d] 
Lsecond = input[d :] 
Rfirst = input[0 : len(input)-d] 
Rsecond = input[len(input)-d : ] 

print( "头部切片翻转 : ", (Lsecond + Lfirst) )
print( "尾部切片翻转 : ", (Rsecond + Rfirst) )

IF name == " main ":
INPUT = 'Runoob'
D = # 2 two characters taken
rotate (input, d)
implementation of the above code is output is:

Flip head sections used: noobRu
tail reversing sections: obRuno
the Python button (key) or the value (value) of the sorting dictionary

Given a dictionary, then the button (key) or the value (value) of the sorting dictionary.

Example 1: key (key) ordering

def dictionairy():

# 声明字典
key_value ={}     

# 初始化
key_value[2] = 56       
key_value[1] = 2 
key_value[5] = 12 
key_value[4] = 24
key_value[6] = 18      
key_value[3] = 323 

print ("按键(key)排序:")   

# sorted(key_value) 返回一个迭代器
# 字典按键排序
for i in sorted (key_value) : 
    print ((i, key_value[i]), end =" ") 

def main():

call function

dictionairy() 

The main function

IF name == " main ":
main ()
or more execution code output is:

Button (key) Sorting:
(1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18)
Example 2: Sort value (value)

def dictionairy():

# 声明字典
key_value ={}     

# 初始化
key_value[2] = 56       
key_value[1] = 2 
key_value[5] = 12 
key_value[4] = 24
key_value[6] = 18      
key_value[3] = 323 

print ("按值(value)排序:")   
print(sorted(key_value.items(), key = lambda kv:(kv[1], kv[0])))   

def main():
dictionairy()

IF name == " main ":
main ()
or more execution code output is:

Sort value (value):
[(. 1, 2), (. 5, 12 is), (. 6, 18 is), (. 4, 24), (2, 56 is), (3, 323)]
Example 3: dictionaries sorted list

lis = [{ "name" : "Taobao", "age" : 100},
{ "name" : "Runoob", "age" : 7 },
{ "name" : "Google", "age" : 100 },
{ "name" : "Wiki" , "age" : 200 }]

By age Ascending

print ( "list in ascending order by age:")
Print (the sorted (LIS, the lambda Key = I: I [ 'age']))

print ("\r")

Sort first by age, then name sort

print ( "List Sort by age and name:")
Print (the sorted (LIS, the lambda Key = I: (I [ 'age'], I [ 'name'])))

print ("\r")

In descending order by age

print ( "Sort Descending List by age:")
Print (the sorted (LIS, the lambda Key = I: I [ 'age'], Reverse = True))
execute the above code output is:

List by age in ascending order:
[{ 'name': 'Runoob', 'age':. 7}, { 'name': 'Taobao', 'age': 100}, { 'name': 'the Google', 'age ': 100}, {' name ':' Wiki ',' age ': 200}]

List by age and name sort:
[{ 'name': 'Runoob', 'age':. 7}, { 'name': 'the Google', 'age': 100}, { 'name': 'Taobao', ' age ': 100}, {' name ':' Wiki ',' age ': 200}]

List by age descending order:
[{ 'name': 'Wiki', 'age': 200 is}, { 'name': 'Taobao', 'age': 100}, { 'name': 'the Google', 'age ': 100}, {' name ':' Runoob ',' Age ':. 7}]
the Python and the calculated values dictionaries

Given a dictionary, and calculating numeric values ​​and all of them.

Examples

def returnSum(myDict):

sum = 0
for i in myDict: 
    sum = sum + myDict[i] 

return sum

= {dict 'A': 100, 'B': 200 is, 'C': 300}
Print ( "the Sum:", returnSum (dict))
execute the above code output is:

SUM: 600
Python dictionary to remove the key points (key / value) pair

Given a dictionary, and calculating numeric values ​​and all of them.

Example 1: Use del removed

test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4}

Output original dictionary

print ( "before removing the dictionary:" + str (test_dict))

Use del removed Zhihu

deltest_dict [ 'Zhihua']

After removal of the output dictionary

print ( "After removing the dictionary:" + str (test_dict))

Do not remove the key will complain

#del test_dict [ 'Baidu']
the above code is output is performed:

Before removing the dictionary: { 'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
After removal of the dictionary: { 'Runoob': 1, 'Google': 2, 'Taobao ': 3}
example 2: pop () removed

test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4}

Output original dictionary

print ( "before removing the dictionary:" + str (test_dict))

Use pop to remove Zhihu

removed_value = test_dict.pop('Zhihu')

After removal of the output dictionary

print ( "After removing the dictionary:" + str (test_dict))

print ( "key corresponding to the removed value is:" + str (removed_value))

print ('\r')

Use pop () to remove the key exception does not happen, we can customize the message

removed_value = test_dict.pop ( 'Baidu', 'not the key (key)')

After removal of the output dictionary

print ( "dictionary after removal:" + STR (test_dict))
print ( "removal value:" + str (removed_value))
execute the above code output is:

Before removing the dictionary: { 'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
After removal of the dictionary: { 'Runoob': 1, 'Google': 2, 'Taobao ': 3}
removing the key corresponding to the value of: 4

After removal of the dictionary: { 'Runoob': 1, 'Google': 2, 'Taobao': 3}
removing value: the absence of the key (key)
Example 3: items () removed

test_dict = {"Runoob" : 1, "Google" : 2, "Taobao" : 3, "Zhihu" : 4}

Output original dictionary

print ( "before removing the dictionary:" + str (test_dict))

Use pop to remove Zhihu

new_dict = {key:valfor key, val in test_dict.items() if key != 'Zhihu'}

#

The output is performed above code:

Before removing the dictionary: { 'Runoob': 1, 'Google': 2, 'Taobao': 3, 'Zhihu': 4}
After removal of the dictionary: { 'Runoob': 1, 'Google': 2, 'Taobao ':. 3}
the Python merge dictionaries

Given a dictionary, and calculating numeric values ​​and all of them.

Example 1: Use update () method, the second parameter combined first parameter

def Merge(dict1, dict2):
return(dict2.update(dict1))

Two dictionaries

dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}

Return None

print(Merge(dict1, dict2))

dict2 merged dict1

print (dict2)
execute the above code output is:

None { 'd': 6, 'c': 4, 'a': 10, 'b': 8}
Example 2: **, function parameters introduced in the form of a dictionary

def Merge(dict1, dict2):
res = {dict1, dict2}
return res

Two dictionaries

= {dict1 'A': 10, 'B':. 8}
dict2 = { 'D':. 6, 'C':}. 4
dict3 = the Merge (dict1, dict2) Print (dict3)
execute the above code output is:

{'a': 10, 'b': 8, 'd': 6, 'c': 4}

Well, I gave everyone here to share the end of the text to share a Bo Fuli

Examples Python3 (VI)

Examples Python3 (VI)

Access: group 839 383 765 plus python can get!

Guess you like

Origin blog.51cto.com/14186420/2407523