专业编程基础技术教程

网站首页 > 基础教程 正文

【PythonTip题库精编300题】第19题:字符串结尾判断

ccvgpt 2024-08-09 12:03:05 基础教程 9 ℃

1、编程试题:

编写一个程序来检查一个字符串是否以另一个字符串结尾。

【PythonTip题库精编300题】第19题:字符串结尾判断

定义函数ends_with(),有两个参数string1和string2。

在函数内,如果string1以string2结尾,则返回True,否则返回False。

2、代码实现:

(1)基础代码:

#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
#
# Copyright (C) 2024 , Inc. All Rights Reserved
#
# @Time      : 2024/1/6 10:02
# @Author    : fangel
# @FileName  : 19. 字符串结尾判断.py
# @Software  : PyCharm

def ends_with(string1, string2):
    len1 = len(string1)
    len2 = len(string2)
    j = 0
    for i in range(len1-len2,len1):
        if(string1[i] != string2[j]):
            return False
        j = j + 1
    return True

# 获取输入字符串
string1 = input()
string2 = input()
# 调用函数
print(ends_with(string1, string2))

(2)直接利用python的内置函数endswith来实现

#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
#
# Copyright (C) 2024 , Inc. All Rights Reserved
#
# @Time      : 2024/1/6 10:02
# @Author    : fangel
# @FileName  : 19. 字符串结尾判断.py
# @Software  : PyCharm

def ends_with(string1, string2):
    if string1.endswith(string2):
        return True
    else:
        return False

# 获取输入字符串
string1 = input()
string2 = input()
# 调用函数
print(ends_with(string1, string2))

3、代码分析:

函数endswith() 作用:判断字符串是否以指定字符或子字符串结尾,常用于判断文件类型

4、运行结果:

(1)

wefgvbty

wefgvbty

True

(2)

ryuiorhygyinhj

inhj

True

(3)

qwer

ert

False

最近发表
标签列表