Strings and lists in Python

Character string

1. Definition of strings:

a = 'westos'
b = "what's"
c = """
    //User Management System
    1.Adding users
    2.delete user
    Three.show user
    ....

"""
print(a)
print(b)
print(c)

[29]

2. Characters of strings:

s = 'hello' # Index: 0 1 2 3 4 index starts from 0
print(s[0])
print(s[1])
# Take out the last character
print(s[4])
print(s[-1])
# s[start:stop:step] from satrt to END-1
# step
print(s[0:3])
print(s[0:4:2])

[30]

# Display all characters
print(s[:])
# Display the first three characters
print(s[:3])
# String inversion
print(s[::-1])

[31]

# All characters except the first character
print(s[1:])

# repeat
print(s * 10)

# Connect
print('hello ' + 'python')

[32]

# Member operator
print('he' in s)
print('aa' in s)
print('he' not in s)

# for loop traversal
for i in s:
    print(i)

[33]

3. Common methods of strings

>>> 'hello'.istitle()
False
>>> 'hello'.isupper()
False
>>> 'Hello'.isupper()
False
>>> 'HELLO'.isupper()
True
>>> 'hello'.islower()
True
>>> 'Hello'.islower()
False
>>> a = 'Hello'.lower()
>>> a
'hello'
>>> a = 'Hello'.upper()
>>> a
'HELLO'
>>> a = 'Hello'.title()
>>> a
'Hello'
>>> 

[34]

e.g.

filename = 'hello.loggg'
if filename.endswith('.log'):
    print(filename)
else:
    print('error.file')

url = 'https://172.2 Five.254.250/index.html'
if url.startswith('http://'):
    print('Crawl content~~')
else:
    print('Can't crawl~~')

[35]

4. String Judgment

[[:digit:]] [[:alpha:]]

e.g. Return to False as long as one element is not satisfied

print('weeeqwe32131'.isdigit())
print('42131321fsas'.isalpha())
print('weewqeq323213'.isalnum())

[3 Six]

e.g. Is the definition of variable names legal?
1. Variable names can be composed of alphanumeric underscores
2. Variable names can only begin with letters or underscores
s = '321csv_' s[0] s[1:]
s = 'asfasf%%'
'_'
exit

while True:
    s = input('Variable name:')
    if s == 'exit':
        print('exit')
        break
    if s[0].isalpha() or s[0] == '_':
        for i in s[1:]:
          if not (i.isalnum() or i == '_'):
              print('%s Illegal variable name' %(s))
              break
        else:
            print('%s Variable Name Legitimacy' %(s))
    else:
        print('%s Illegal variable name' %(s))

[37]

5. Alignment of strings

print('Student Management System'.center(30))
print('Student Management System'.center(30,'@'))
print('Student Management System'.center(30,'&'))
print('Student Management System'.ljust(30,'#'))
print('Student Management System'.rjust(30,'#'))

[38]

6. Replacement of strings

e.g.

s = 'hello world hello'

# find finds the substring and returns the smallest index
print(s.find('hello'))
print(s.find('world'))
print(s.find('hello'))

# Replace the hello in the string with redhat
print(s.replace('hello','redhat'))

[39]

7. String statistics

e.g.

print('hello'.count('l'))
print('hello'.count('ll'))
print(len('wfqfqfqfq'))

[40]

8. Separation and Connection of Strings

s = '172.25.254.250'
s1 = s.split('.')
print(s1)
print(s1[::-1])

date = '2019-8-28'
date1 = date.split('-')
print(date1)

# Connections connect each character through a specified connection symbol
print(''.join(date1))
print('/'.join(date1))
print('~~'.join('hello'))

[41]

e.g. String Exercise
Millet Written Test Programming

- Title Description:
> Given a sentence (containing only letters and spaces), invert the position of words in the sentence.
Words are divided into spaces. There is only one space between words. There are no spaces before and after the words.
For example: (1) "hello xiao mi" - > "mi xiao hello"
- Input Description: 
> The input data consists of multiple groups, each of which takes up one line and contains a sentence (the len gt h of the sentence is less than 1000 characters).
- Output description: 
> For each test example, a sentence formed by inversion of words in a sentence is required to be output.
Example 1:
input
    hello xiao mi
 output
    mi xiao hello

print(' '.join(input().split()[::-1]))

[42]

list

1. List creation

Array: Set scores that store the same data type = 34, 56, 90, 100.]
List (an array of hormones): Any data type can be stored

list = [1,1.2,True,'westos']
print(list,type(list))

# Lists can also be nested
list2 = [1,1.2,True,'westos',[1,2,3,4]]
print(list2,type(list2))

[43]

2. Characteristic of lists

service = ['http','ftp','ssh']

# Indexes
# Forward Index
print(service[0])
# Reverse Index
print(service[-1])

# Section
print(service[::-1])
print(service[1:])
print(service[:-1])

# repeat
print(service * 3)

# Connect
service1 = ['mysql','firewalld']
print(service + service1)

# Member operator
print('firewalld' in service)
print('ftp' not in service1)

[44]

e.g. Assume the following list:

names = ['fentiao', 'fendai', 'fensi', 'apple']
//The output is:'I have fentiao, fendai, fensi and apple. '

names = ['fentiao', 'fendai', 'fensi', 'apple']
print('I have ' + ','.join(names[:-1]) + ' and ' + names[-1])

[45]

e.g. Enter yyyy-MM-dd to determine the date of the year.

cal = input('Please enter the date yyyy-MM-dd: ')
date = cal.split('-') #Split Date
#print(date)
year = int(date[0])
month = int(date[1])
day = int(date[2])
arr = [0,31,28,31,30,31,30,31,31,30,31,30,31]
num = 0
if ((year % 4 ==0) and (year % 100 !=0) or (year % 400 ==0)):
    arr[2] = 29
for i in range(1,len(arr)):
    if month > i:
        num += arr[i]
    else:
        num += day
        break
print('Days:',num)

[46]

3. Increase in list elements

service = ['http','ftp','ssh']

# append(): append an element to the list
service.append('firewalld')
print(service)

# extend(): Stretching adds multiple elements to the list
service.extend(['mysql','nfs'])
print(service)

# insert(): Insert elements at the specified index
service.insert(1,'https')
print(service)

[47]

4. Delete List Elements

>>> service = ['http','ftp','ssh']
>>> service.pop()
'ssh'
>>> service
['http', 'ftp']
>>> service.pop()
'ftp'
>>> service
['http']
>>> service = ['http','ftp','ssh']
>>> service.pop(0)
'http'
>>> service
['ftp', 'ssh']
>>> a = service.pop()
>>> a
'ssh'
>>> 

[48]

# remove(): Delete list elements
service = ['http','ftp','ssh']
service.remove('ftp')
print(service)
# print(a)

# Delete an element from memory
del service[1]
print(service)

[49]

5. Viewing Lists

service = ['http','samba','nfs','iscsi','http']

# View the number of occurrences
print(service.count('http'))

# View the index value of the specified element (you can specify the index range)
print(service.index('nfs'))
print(service.index('http'))
print(service.index('http',2,5))

[50]

6. List modification

service = ['http','samba','nfs']
# Re-assignment by index
service [0] = 'mysql'
print(service)

# Index slice repetitive join member operator can be iterated
# By slicing
print(service[:2])
service[:2] = ['firewalld','iscsi']
print(service[:2])

[51]

7. Listing

import random
# Sort by ASCII code
service = ['http','samba','nfs','iscsi','http']
service.sort()
print(service)

li = list(range(10))
print(li)

random.shuffle(li)   # Upset
print(li)

[52]

e.g. Implementation of User Management

1.Background Administrator User: admin´╝îPassword: westos
2.After the administrator logs in, user information can be managed
3.User information includes: adding user information, deleting user information, viewing user information, exiting
4.Initialize user information:
users = ['root','redhat']
passwd = ['123','456']

print('Administrator login'.center(50,'*'))
aduser = input('Username: ')
adpasswd = input('Password: ')

#System user information
users = ['root','redhat']
passwd = ['123','456']

if aduser == 'admin' and adpasswd == 'westos':
    print('Administrator logged in successfully!')
    print('User login'.center(50, '*'))
    while True:
        print("""
            //menu
        1.Adding user information
        2.Delete user information
        3.View user information
        4.Sign out
        """)
        choice = input('Please enter your choice: ')
        if choice == '1':
            print('Adding user information'.center(50,'*'))
            adduser = input('Add User Name: ')
            if adduser in users:
                # print('user% s already exists'% adduser)
                print(f"user{adduser}It already exists.")
            else:
                addpasswd = input('Password: ')
                users.append(adduser)
                passwd.append(addpasswd)
                print(f"user{adduser}Added Successfully")

        elif choice == '2':
            print('Delete user information'.center(50, '*'))
            deluser = input('Delete user name: ')
            if deluser in users:
                delindex = users.index(deluser)
                users.remove(deluser)
                passwd.pop(delindex)
                print(f"delete user{deluser}Success")
            else:
                print(f"user{deluser}Non-existent")

        elif choice == '3':
            print('View user information'.center(50, '*'))
            print('\t User name\t Password')
            userlenth = len(users)
            for i in range(userlenth):
                print('\t%s\t%s' %(users[i],passwd[i]))

        elif choice == '4':
            exit()

        else:
            print('Please enter the correct choice!')
else:
    print('Administrator login failure!')

[53]

Implementation of e.g. Stack

1.Push
2.Stack out
3.Stack top element
4.Stack Length
5.Is the stack empty?

stack = []
print('Implementation of stack'.center(50,'*'))
while True:
    print("""
        //menu
        1.Push        2.Stack out          3.Stack top element
        4.Stack length        5.Is the stack empty?     6.Sign out
    """)
    choice = int(input('Please enter functional options:'))
    if choice == 1:
        print('The current stack is:%s' %stack)
        addele = str(input('Please enter the stack element:'))
        stack.append(addele)
        print(f"element{addele}It's on the stack!")
    elif choice == 2:
        print('The current stack is:%s' %stack)
        if len(stack) == 0:
            print('Stack empty! Unable to perform stack-out operation!')
        else:
            delele = stack[-1]
            stack.pop()
            print(f"element{delele}Out of the stack!")
            print('The new stack after the stack operation is:%s' %stack)
    elif choice == 3:
        if len(stack) == 0:
            print('Stack empty! No top element!')
        else:
            top = stack[-1]
            print('The current stack is:%s' %stack)
            print('The top element of the stack is:%s' %top)
    elif choice == 4:
        length = len(stack)
        print('The current stack is:%s' %stack)
        print('The stack length is%d' %length)
    elif choice == 5:
        if len(stack) == 0 :
            print('Stack empty!')
        else:
            print('The current stack is:%s' %stack)
            print('This stack is not empty!')
    elif choice == 6:
        print('Sign out!')
        break
    else:
        print('Please enter the correct function options!')

[54]

Built-in methods commonly used in python

In [8]: min(2,3,4,5)                                                    
Out[8]: 2

In [9]: max(2,3,4,5)                                                    
Out[9]: 5

In [10]: sum(range(1,101))                                              
Out[10]: 5050

In [11]: sum(range(1,101,2))                                            
Out[11]: 2500

In [12]: sum(range(2,101,2))                                            
Out[12]: 2550

#Enumeration: Returns index values and corresponding value values
for i,v in enumerate('westos'):
    print(i,v)

#zip
s1 = 'abc'
s2 = '123'

for i in zip(s1,s2):
    # print(i)
    print(' '.join(i))

[55]

Tags: ftp ssh MySQL Python

Posted on Mon, 09 Sep 2019 05:01:10 -0700 by __greg