Python programming exercises (4)

Table of contents

1. Find a number within 10,000 that is divisible by 5 or 6, but not both at the same time. 

2. Write a method to calculate the sum of all even-numbered elements in the list

3. Remove spaces from each string in the string array

4. Split the string into lines based on punctuation marks

5. Let the user enter a date format such as "2008/08/08" and convert the entered date format to "2008-August-8th"

6. Receive the string input by the user, sort the characters (in ascending order), and output it in reverse order, "cabed" → "abcde" → "edcba".

7. Receive an English sentence input by the user and output the words in reverse order, "hello c sharp" → "sharp c hello".

8. Extract the username and domain name from the request address http://www.163.com?userName=admin&pwd=123456

9. How to determine whether a string is a substring of another string? Find() index() double-layer loop is completed? ?

10. How to randomly generate a string of letters without numbers

11. How to randomly generate strings with numbers and letters

12. How to determine whether a string contains both numbers and letters

13. Sorting of characters within a string (only in alphabetical order regardless of case)

14. Determine whether a character is a palindrome string

15. Enter any book title you have in mind, and then output its string length

16. Let the user enter a sentence and find all the locations of "he".

17. Let the user enter a sentence and find all the locations of "hehe".

18. Two students enter their favorite game names and judge whether they are consistent. If they are equal, output the game that you two like the same. If they are not the same, output the games that you two like different. The two students enter lol and LOL stands for the same game

19. Let the user input a sentence and determine whether there is evil in the sentence. If there is evil, replace it with this form and output it, such as: "Lao Niu is very evil", and after output it becomes "Lao Niu is very **";


1. Find a number within 10,000 that is divisible by 5 or 6, but not both at the same time.

def func():
    for i in range(1, 10000):
        if i % 5 == 0 or i % 6 == 0:
            if i % 5 == 0 and i % 6 == 0:
                continue
        print(i)


func()

2. Write a method to calculate the sum of all even-numbered elements in the list

def sum_even(ls):
    sum_even = 0
    for i in range(0, len(ls), 2):
        sum_even += ls[i]
    return sum_even


if __name__ == '__main__':
    ls = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    print(f'{ls}中所有偶数下标元素的和为:{sum_even(ls)}')

3. Remove spaces from each string in the string array

def cls_space(strings):
    for i in range(len(strings)):
        strings[i] = strings[i].replace(' ', '')
    return strings


if __name__ == '__main__':
    strings = input('请输入多个字符串:').split(',')
    print(f'您输入的字符串数组:{strings}')
    print(f'清除空格后的字符串数组:{cls_space(strings)}')

4. Split the string into lines based on punctuation marks

def enter(fh, string):
    tmp = string.split(f'{fh}')
    for i in range(len(tmp)):
        print(tmp[i])


if __name__ == '__main__':
    string = input('请输入一段带有标点符号的字符串:')
    fh = input('请输入换行标志符号:')
    enter(fh, string)

5. Let the user enter a date format such as "2008/08/08" and convert the entered date format to "2008-August-8th"

def swich_date(one_date):

    tmp = one_date.split('/')
    print(f'{tmp[0]}年-{int(tmp[1])}月-{int(tmp[2])}日')


if __name__ == '__main__':
    one_date = input('请输入“年/月/日”格式的日期:')
    swich_date(one_date)

6. Receive the string input by the user, sort the characters (in ascending order), and output it in reverse order, "cabed" → "abcde" → "edcba".

def sort_reverse(str):

    tmp = list(str)
    tmp.sort(reverse=True)
    str_1 = ''.join(tmp)
    return str_1


if __name__ == '__main__':
    str = input('请输入一个英文字符串:')
    print(f'您输入的字符串为:{str}')
    print(f'逆序排序后的字符串为:{sort_reverse(str)}')

7. Receive an English sentence input by the user and output the words in reverse order, "hello c sharp" → "sharp c hello".

def sentence_reverse(sentence):
    tmp = sentence.split(' ')
    tmp.reverse()
    senrence = ' '.join(tmp)
    return senrence


if __name__ == '__main__':
    sentence = input('请输入一句英文:')
    print(f'逆序输出:{sentence_reverse(sentence)}')

8. Extract the username and domain name from the request address http://www.163.com?userName=admin&pwd=123456

url = 'http://www.163.com?userName=admin&pwd=123456'

ls = url.split('?')
domain = ls[0].split('/')[2]
ls_1 = ls[1].split('&')
username = ls_1[0].split('=')[1]
print(f'域名:{domain}')
print(f'域名:{username}')

9. How to determine whether a string is a substring of another string? Find() index() double-layer loop is completed? ?

str_a = input('请输入字符串a:')
str_b = input('请输入字符串b:')

# 使用find()方法:
flag = str_a.find(str_b)
if flag == -1:
    print('字符串b不是字符串a的子串')
else:
    print('字符串b是字符串a的子串')

# 使用index()方法:
try:
    flag = str_a.index(str_b)
except ValueError:
    print('字符串b不是字符串a的子串')
else:
    print('字符串b是字符串a的子串')

10. How to randomly generate a string of letters without numbers

import random


def random_letter():
    ls = []
    str_max = int(input('请输入随机字符串长度的最大值:'))
    str_len = random.randint(1, str_max)
    for i in range(str_len):
        ls.append(chr(random.randint(ord('a'), ord('z'))))
    strs = ''.join(ls)
    return strs


if __name__ == '__main__':
    print(random_letter())

11. How to randomly generate strings with numbers and letters

import random


def random_letter():
    letter = chr(random.randint(ord('a'), ord('z')))
    return letter


def random_num09():
    num = random.randint(0, 9)
    return num


if __name__ == '__main__':
    ls = []
    str_max = int(input('请输入随机字符串长度的最大值:'))
    str_len = random.randint(1, str_max)
    for i in range(str_len):
        flag = random.randint(0, 1)
        if flag == 0:
            ls.append(str(random_num09()))
        else:
            ls.append(random_letter())
    strs = ''.join(ls)
    print(strs)

12. How to determine whether a string contains both numbers and letters

def num_alpha(str):
    flag_num = 0
    flag_alpha = 0
    for i in str:
        if i.isdigit():
            flag_num = 1
            break
    for i in str:
        if i.isalpha():
            flag_alpha = 1
            break
    if flag_num == 1 and flag_alpha == 1:
        return True
    else:
        return False


if __name__ == '__main__':
    str = input('请输入一个字符串:')
    if num_alpha(str):
        print('该字符串中既有数字又有字母')
    else:
        print('该字符串不满足既有数字又有字母')

13. Sorting of characters within a string (only in alphabetical order regardless of case)

def alp_sort(str):
    ls = list(str)
    ls_upper = []
    for i in range(len(str)):
        if ls[i].isalpha:
            if ls[i].isupper():
                ls_upper.append(ls[i])
                ls[i] = ls[i].lower()
    ls.sort()
    for i in ls_upper:
        flag = ls.index(i.lower())
        ls[flag] = ls[flag].upper()
    str = ''.join(ls)
    return str


if __name__ == '__main__':
    str = input('请输入一段字符串:')
    print(f'排序后的字符串:{alp_sort(str)}')

14. Determine whether a character is a palindrome string

def isHuiWen(str):
    ls_1 = list(str)
    ls_2 = list(str)
    ls_2.reverse()
    if ls_1 == ls_2:
        print('该函数是回文字符串')
    else:
        print('该函数不是回文字符串')


if __name__ == '__main__':
    str = input('请输入一个字符串:')
    isHuiWen(str)

15. Enter any book title you have in mind, and then output its string length

def length(book_name):
    l = len(book_name)
    print("你心中的书名长度是:", l)


length("活着")

16. Let the user enter a sentence and find all the locations of "he".

def find_all(string, sub):
    start = 0
    pos = []
    while True:
        start = string.find(sub, start)
        if start == -1:
            return pos
        pos.append(start)
        start += len(sub)


print(find_all('今天真的呵呵呵呵呵呵呵呵呵呵', '呵'))

17. Let the user enter a sentence and find all the locations of "hehe".

def find_all(string, sub):
    start = 0
    pos = []
    while True:
        start = string.find(sub, start)
        if start == -1:
            return pos
        pos.append(start)
        start += len(sub)


print(find_all('今天真的呵呵欧呵呵欧呵呵欧呵呵欧呵呵', '呵呵'))

18. Two students enter their favorite game names and judge whether they are consistent. If they are equal, output the game that you two like the same. If they are not the same, output the games that you two like different. The two students enter lol and LOL stands for the same game

a = input('请输入甲同学喜欢的游戏:')
b = input('请输入乙同学喜欢的游戏:')
if a.lower() == b.lower():
    print('你们喜欢相同的游戏')
else:
    print('你们喜欢不同的游戏')

19. Let the user input a sentence and determine whether there is evil in the sentence. If there is evil, replace it with this form and output it, such as: "Lao Niu is very evil", and after output it becomes "Lao Niu is very **";

a = input("请输入一句话:")
for i in range(0, len(a)-1):
    if a[i] == "邪":
        if a[i+1] == '恶':
            a = a.replace("邪", "*")
            a = a.replace("恶", "*")
            break

print(a)

Guess you like

Origin blog.csdn.net/weixin_62304542/article/details/129992081