You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为未以.gif结尾的字符串添加.gif后缀?

为字符串添加.gif后缀的实现方案

针对你的需求——判断字符串是否以.gif结尾,若未结尾则添加该后缀,以下是几种常见编程语言的实现方式:

Python 实现

利用字符串的endswith()方法直接判断后缀:

foo = "/this/is a/path/my file.gif"
bar = "/this/is a/path/my file"

def add_gif_suffix(s):
    # 检查是否已以.gif结尾
    if not s.endswith('.gif'):
        return s + '.gif'
    return s

# 处理变量
foo_updated = add_gif_suffix(foo)
bar_updated = add_gif_suffix(bar)

print(foo_updated)  # 输出: /this/is a/path/my file.gif
print(bar_updated)  # 输出: /this/is a/path/my file.gif

JavaScript 实现

使用字符串的endsWith()方法进行判断:

const foo = "/this/is a/path/my file.gif";
const bar = "/this/is a/path/my file";

function addGifSuffix(str) {
    return str.endsWith('.gif') ? str : str + '.gif';
}

const fooUpdated = addGifSuffix(foo);
const barUpdated = addGifSuffix(bar);

console.log(fooUpdated); // 输出: /this/is a/path/my file.gif
console.log(barUpdated); // 输出: /this/is a/path/my file.gif

Bash 实现

通过条件判断结合字符串匹配实现:

foo="/this/is a/path/my file.gif"
bar="/this/is a/path/my file"

add_gif_suffix() {
    local input="$1"
    # 匹配是否以.gif结尾
    if [[ "$input" != *.gif ]]; then
        echo "$input.gif"
    else
        echo "$input"
    fi
}

foo_updated=$(add_gif_suffix "$foo")
bar_updated=$(add_gif_suffix "$bar")

echo "$foo_updated"  # 输出: /this/is a/path/my file.gif
echo "$bar_updated"  # 输出: /this/is a/path/my file.gif

核心逻辑说明

所有实现的核心都是两步:

  • 判断后缀:检查目标字符串是否已经以.gif结尾
  • 添加后缀:如果没有,则在字符串末尾拼接.gif;如果已有,则直接返回原字符串

内容的提问来源于stack exchange,提问作者Ahmad Ismail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 00:54:09