首页 > 解决方案 > 为变量 Python 提供最大/最小字符数(字符串)

问题描述

代码中有一些法语,但不用担心,我在这里唯一想做的就是添加一些内容,以防止我在 ch1 中输入小于 4 的字符串,在 ch2 中输入至少 1 个字符。这段代码适用于我正在做的事情。

ch1 = input("Entre the first chain:")
ch2 = input('Enter the second chain:')
resultat = 0
sub_len = len(ch2)


for i in range(len(ch1)):
    if ch1[i:i+sub_len] == ch2:
        resultat += 1

print('Chaîne 1 saisie: {}'.format(ch1))
print('Chaîne 2 saisie: {}'.format(ch2))
print('Réponse: La chaîne 2 se retrouve {} fois dans la châine 1.'.format(resultat))

标签: pythonstring

解决方案


您必须自己测试输入字符串的长度,如果输入无效,则在循环中重复输入。

一种方法:

while True:
    ch1 = input("Entre the first chain: (minimum 4 chars)")
    if len(ch1) >= 4:
        break

while True:
    ch2 = input('Enter the second chain (minimum 1 char):')
    if len(ch2) >= 1:
        break

推荐阅读