Python (palindrome determination, match the same file at the beginning of the string and the like, it is determined whether the variable is valid)

A: to determine whether the palindrome

Palindrome is being read with the opposite of the reading is the same as Example 1:
Input: 121
Output: true Example 2:
Input: -121
Output: false
explanation: read from left to right, as -121. Reading from right to left, as 121-. So it is not a palindrome number.

num = input('Num:')
if num == num[::-1]:
    print('这是一个回文数')
else:
    print('这不是一个回文数')

Here Insert Picture Description

II: start of the string files in the same

Match the same file at the beginning of the string:

filename = 'hello.loggg'

if filename.endswith('.log'):
     print(filename)
 else:
    print('error filename')

Here Insert Picture DescriptionMatching the same URL beginning of a string:

url1 = 'file:///mnt'
url2 = 'ftp://172.25.254.250/pub'
url3 = 'http://172.25.254.250/index.html'

if url3.startswith('http://'):
    print('获取网页')
else:
    print('未找到网页')

Here Insert Picture Description

Three: to determine whether a variable is legal

The variable name is legitimate:
1. Variable names can consist of letters, numbers, or underscores
2. Variable names can only begin with a letter or an underscore

thought:

1. The first element is determined whether the variable name is the letter or underscore S [0]
2. If the first element is eligible, is determined in addition to the first element of the other elements s [1:]

Implementation process:

# 1 The first character of the variable name is a letter or an underscore
. # 2 If yes, continue to determine -> 4
. # 3 If not, an error
. # 4 followed by a character other than the first judgment of other characters
# 5 determines whether alphanumeric or underscores

while True:
    s = input('变量名:')
    if s == 'exit':
        print('欢迎下次使用')
        break
    if s[0].isalpha() or s[0] == '_':
        for i in s[1:]:
            if not(i.isalnum() or i == '_'):
                print('%s变量名不合法' %s)
                break
        else:
            print('%s变量名合法' %s)
    else:
        print('%s变量名不合法' %s)

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/bmengmeng/article/details/94012036