判断字符串是否包含子串,居然有七种方法?

Python 正则表达式:检查字符串是否只含指定字符 在 Python 中,re 模块提供了一个强大的正则表达式引擎,可以让我们用最小的代码量来实现复杂的字符串匹配和操作。如果我们需要检查一个字符串是否只包含指定的字符,可以使用类似于上面的代码来实现。正则表达式是一种由字符和操作符组成的模式,通常用于匹配文本中的一部分或全部内容。如果匹配成功,则 re.match 函数返回一个 Match 对象,否则返回 None。,并返回一个布尔值,表示这个字符串是否只由数字字符组成。,它表示匹配字符串开头和结尾之间的所有数字字符。表示匹配前面的字符一个或多个, 阅读详情


1、使用 in 和 not in

in 和 not in 在 Python 中是很常用的关键字,我们将它们归类为 成员运算符。

使用这两个成员运算符,可以很让我们很直观清晰的判断一个对象是否在另一个对象中,示例如下:

>>> "llo" in "hello, python"
True
>>>
>>> "lol" in "hello, python"
False

2、使用 find 方法

使用 字符串 对象的 find 方法,如果有找到子串,就可以返回指定子串在字符串中的出现位置,如果没有找到,就返回 -1

>>> "hello, python".find("llo") != -1
True
>>> "hello, python".find("lol") != -1
False
>>

3、使用 index 方法

字符串对象有一个 index 方法,可以返回指定子串在该字符串中第一次出现的索引,如果没有找到会抛出异常,因此使用时需要注意捕获。

def is_in(full_str, sub_str):
    try:
        full_str.index(sub_str)
        return True
    except ValueError:
        return False

print(is_in("hello, python", "llo"))  # True
print(is_in("hello, python", "lol"))  # False

4、使用 count 方法

利用和 index 这种曲线救国的思路,同样我们可以使用 count 的方法来判断。

只要判断结果大于 0 就说明子串存在于字符串中。

def is_in(full_str, sub_str):
    return full_str.count(sub_str) > 0

print(is_in("hello, python", "llo"))  # True
print(is_in("hello, python", "lol"))  # False

5、通过魔法方法

在第一种方法中,我们使用 in 和 not in 判断一个子串是否存在于另一个字符中,实际上当你使用 in 和 not in 时,Python 解释器会先去检查该对象是否有 __contains__ 魔法方法。

若有就执行它,若没有,Python 就自动会迭代整个序列,只要找到了需要的一项就返回 True 。

示例如下;

>>> "hello, python".__contains__("llo")
True
>>>
>>> "hello, python".__contains__("lol")
False
>>>

这个用法与使用 in 和 not in 没有区别,但不排除有人会特意写成这样来增加代码的理解难度。

6、借助 operator

operator模块是python中内置的操作符函数接口,它定义了一些算术和比较内置操作的函数。operator模块是用c实现的,所以执行速度比 python 代码快。

在 operator 中有一个方法 contains 可以很方便地判断子串是否在字符串中。

>>> import operator
>>>
>>> operator.contains("hello, python", "llo")
True
>>> operator.contains("hello, python", "lol")
False
>>> 

7、使用正则匹配

说到查找功能,那正则绝对可以说是专业的工具,多复杂的查找规则,都能满足你。

对于判断字符串是否存在于另一个字符串中的这个需求,使用正则简直就是大材小用。

import re

def is_in(full_str, sub_str):
    if re.findall(sub_str, full_str):
        return True
    else:
        return False

print(is_in("hello, python", "llo"))  # True
print(is_in("hello, python", "lol"))  # False

国产FPGA逆袭!深度评测复旦微RFVU3P5G核心板在相控阵雷达中的表现 本文深度评测了复旦微RFVU3P5G核心板在相控阵雷达中的实战表现。该核心板凭借射频直采架构、高采样率ADC/DAC及丰富的DSP资源,在多通道同步精度、动态范围及系统稳定性等关键指标上表现出色,展现了国产FPGA在高端雷达应用中的硬核实力与供应链自主价值。 阅读详情

相关推荐

骁龙X Elite笔记本重装Windows 11 Arm64系统完整指南与避坑手册

UEFI安全启动和Arm64架构是理解现代计算设备系统部署的基础。UEFI取代传统BIOS,提供了更安全的启动环境和模块化固件接口,而Arm64架构则以其高能效特性,在移动和新兴PC领域日益重要。其技术价值在于为设备带来更快的启动速度、更强的安全防护以及更优的功耗表现。在应用场景上,这直接关系到搭载高通骁龙X Elite等Arm处理器的笔记本电脑的系统安装与维护。对于这类设备,重装系统远非插入通用安装盘那么简单,核心挑战在于必须使用专为Arm64编译的Windows镜像,并需提前集成芯片组、网络等硬件的专属

weixin_33428613的博客 490

判断字符串中是否包含某个字符串

方法一:indexOf()(常用) indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。 如果没有找到匹配的字符串则返回 -1。 注意: indexOf() 方法区分大小写。 var word = ‘@@全部内容’ console.log(word.indexOf("全部内容") != -1) //true 方法二:search() search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。 如果没有找到任何匹配的子串,则返回 -1

夏微微的博客 4万+

JavaFX Stage

JavaFXStagejavafx.stage.Stage表示 JavaFX 桌面应用程序中的窗口。在 JavaFX 内部,Stage您可以插入一个 JavaFX Scene,它表示在窗口内显示的内容 - 在Stage.当 JavaFX 应用程序启动时,它会创建一个根Stage对象,该对象将传递给 start(Stage primaryStage)JavaFX 应用程序的根类的方法。此Stage 对象代表 JavaFX 应用程序的主窗口。

2012年开始工作,全栈开发老兵,目前已是一个老师,分享这么多年的心得体会 508

四种方法可以实现判断字符串包含某个字符

search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。如果没有找到任何匹配的子串,则返回 -1。exec() 方法用于检索字符串中的正则表达式的匹配。返回一个数组,其中存放匹配的结果。如果未找到匹配,则返回值为 null。match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。test() 方法用于检索字符串中指定的值。var reg = RegExp(/组/);var groupName="小白A组";

Ruby_One的博客 2万+

YOLOv11改进策略【损失函数篇】| 将激活函数替换为带有注意力机制的激活函数 ARelu

将ELSA中的函数Φ\PhiΦ用具有可学习参数α\alphaα和β\betaβ的网络层表示为LxiαβCαxixi0σβxixi≥0Lxi​αβCαxi​σβxi​​xi​0xi​≥0​,结合标准的Rectified Linear UnitsRxi0xi0xixi≥0Rxi​0xi​​xi​0xi​≥0​,得到可学习激活函数Fxiα。

Limiiiing的博客 2117

用Python爬取政府采购信息的实战全流程

以 Playwright 自动采集政府采购信息结构化存储与查询可拓展关键词过滤与通知机制。

2201_76125261的博客 1150

JS中判断某个字符串、数组等是否包含某个值

includes() 方法indexOf() 方法find() 方法some() 方法你可以根据自己的需求来选择其中一种方式。如果你使用的是 ES6 或以上的版本,建议使用 includes() 方法或 find() 方法,它们更加直观和便捷;如果你需要兼容 ES5 或更早的版本,那么可以使用 indexOf() 方法或 some() 方法。

m0_64729384的博客 5103

hive get_json_object解析json结果为null咋办?

最近一位开发的同学在使用get_json_object函数对json数据解析的时候,出现了结果为null的问题,问题原因是sql语法导致的,那么今天就来详细介绍一下解析json函数的用法!最后还是提醒小伙伴们,在开发过程中,一定要注意sql语法格式的书写,避免一些意想不到的结果!

笑看风云路的博客 2308

判断一个字符串中是否包含另一个字符串

contains()判断一个字符串中是否包含某个字符串 starsWith()判断一个字符串中是否以某个字符串开始 endsWith()判断一个字符串中是否以某个字符串结尾 var s = "hello world!";s.starsWith("hello"); //true s.endWith("!"); //true s.contains("o"); //true

马优晨 5万+

下采样优化实战:用ADown显著提升YOLOv11的多尺度特征保持能力

ADown 以“可编程梯度信息+多分支特征融合”打破了传统下采样的性能壁垒,为 YOLOv11 带来了多尺度特征的精准传递能力。从原理到代码集成,本教程已为你铺就了一条“小目标检测精度跃升”的实战路径。现在就动手尝试吧——当你看到模型对极小目标也能精准识别,且特征图细节完整时,你会明白这份技术探索的价值。我很乐意在你实践过程中帮你解决任何问题,让我们一起推动目标检测在下采样领域的边界。

FJN110的博客 423

Lammps模拟剪切作用下的位错滑移

Lammps模拟位错与障碍物作用。在lammps中实现周期性位错阵列模型模拟剪切作用下1/2刃位错与障碍物的交互作用

Rockyoung 3461

python七种方法判断字符串是否包含子串

更多编程教程请到:菜鸟教程 https://www.piaodoo.com/ 友情链接: 高州阳光论坛https://www.hnthzk.com/ 1. 使用 in 和 not in in 和 not in 在 Python 中是很常用的关键字,我们将它们归类为 成员运算符。 使用这两个成员运算符,可以很让我们很直观清晰的判断一个对象是否在另一个对象中,示例如下: >>> "llo" in "hello, python" True >>> >&

菜鸟教程 3128

机器人控制算法九之 位姿描述与空间变换

机器人控制算法九之 位姿描述与空间变换

yohnyang的博客 1034

python 子串是否在字符串中_python七种方法判断字符串是否包含子串

1. 使用 in 和 not inin 和 not in 在 Python 中是很常用的关键字,我们将它们归类为 成员运算符。使用这两个成员运算符,可以很让我们很直观清晰的判断一个对象是否在另一个对象中,示例如下:>>> "llo" in "hello, python"True>>>>>> "lol" in "hello, python"Fal...

weixin_39640024的博客 2659

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

python子串是什么_python七种方法判断字符串是否包含子串

1. 使用 in 和 not inin 和 not in 在 Python 中是很常用的关键字,我们将它们归类为 成员运算符。使用这两个成员运算符,可以很让我们很直观清晰的判断一个对象是否在另一个对象中,示例如下:>>> "llo" in "hello, python"True>>>>>> "lol" in "hello, python"Fal...

weixin_39949386的博客 766

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

python正则判断字符串_python七种方法判断字符串是否包含子串

1. 使用 in 和 not inin 和 not in 在 Python 中是很常用的关键字,我们将它们归类为 成员运算符。使用这两个成员运算符,可以很让我们很直观清晰的判断一个对象是否在另一个对象中,示例如下:2. 使用 find 方法使用 字符串 对象的 find 方法,如果有找到子串,就可以返回指定子串在字符串中的出现位置,如果没有找到,就返回 -13. 使用 index 方法字符串对象有...

weixin_39857792的博客 1509

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

python判断子串_Python 判断字符串是否包含子串,居然有七种方法?

1、使用 in 和 not inin 和 not in 在 Python 中是很常用的关键字,我们将它们归类为 成员运算符。使用这两个成员运算符,可以很让我们很直观清晰的判断一个对象是否在另一个对象中,示例如下:>>>"llo"in"hello,python"True>>>>>>"lol"in"hello,python"False2...

weixin_34061587的博客 2972

【python】判断字符串是否包含子串,居然有七种方法?

1、使用 in 和 not inin和not in在 Python 中是很常用的关键字,我们将它们归类为成员运算符。

2301_76161259的博客 1947

中判断字符串是否包含某个字符_Python 判断字符串是否包含子串,居然有七种方法?...

点击上方“Python编程时光”,选择“加为星标”第一时间关注Python技术干货!系列导读Python 炫技操作(01):条件语句的七种写法Python 炫技操作(02):合并字典的七种方法Python 炫技操作(03):连接列表的八种方法Python 炫技操作(04):海象运算符的三种方法Python 炫技操作(05):花式导包的八种方法1、使用 in 和 not inin 和 no...

weixin_33966205的博客 2196

中判断字符串是否为空_判断字符串是否包含子串,居然有七种方法?

系列导读Python 炫技操作(01):条件语句的七种写法Python 炫技操作(02):合并字典的七种方法Python 炫技操作(03):连接列表的八种方法Python 炫技操作(04):海象运算符的三种方法Python 炫技操作(05):花式导包的八种方法1、使用 in 和 not inin 和 not in 在 Python 中是很常用的关键字,我们将它们归类为 成员运算符。使用这...

weixin_30440721的博客 216

aspx 判断字符串是否为decimal_判断字符串是否包含子串,居然有七种方法?

码小辫专注更多编程视频和电子书天天在用钱1、使用 in 和 not inin 和 not in 在 Python 中是很常用的关键字,我们将它们归类为 成员运算符。使用这两个成员运算符,可以很让我们很直观清晰的判断一个对象是否在另一个对象中,示例如下:>>>"llo"in"hello,python"True>>>>>>"lo...

weixin_39980711的博客 154

aspx 判断字符串是否为decimal_Python 判断字符串是否包含子串,居然有七种方法?...

点击上方“Python编程时光”,选择“加为星标”第一时间关注Python技术干货!系列导读Python 炫技操作(01):条件语句的七种写法Python 炫技操作(02):合并字典的七种方法Python 炫技操作(03):连接列表的八种方法Python 炫技操作(04):海象运算符的三种方法Python 炫技操作(05):花式导包的八种方法1、使用 in 和 not inin 和 no...

weixin_39918248的博客 227

Python 判断一个字符串是否包含另一个子字符串和有多少个子字符串(全网最全 七种方法)

判断字符串中是否有某个子串 这里有六个方法 不使用string模块 1.in 存在则输出TRUE 不存在则输出FALSE a = 'love you' b = 'you' c = 'no' print(b in a) #True print(c in a) #False 2.find() 从左向右查找子串 存在则输出子串首字符的索引值 不存在则输出-1 a = 'love you' b = '...

weixin_44929977的博客 8878
上一篇: Pandas官方文档!(中文版PDF下载)
下一篇: 《Python知识手册》.pdf
Wang_AI
博客等级 码龄12年 996粉丝 162原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值