Python字符串d

2024-09-28 23:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个问题:

1.我有一个字符串,我想要一个函数,在a$中搜索第一次出现的b$,并在第一次出现的b$之前返回a$的字符,如下所示:

Input: MISSISSIPPI,P ==> OUTPUT==>MISSISSI

我做了一个程序,但只删除了这样一个字符串

word=input("Add word: ")
m=input("Add char:  ")
import re
removed=word.replace(m,"")
print(removed)

Input:MISSISSIPPi ==> Output:MISSISSII

我还想删除最后一个"i"

2.另一个问题是字符串,我想在每次找到字符b$时将给定的字符串(a$)拆分为子字符串。你知道吗


Tags: 函数字符串import程序readdinputoutput
3条回答

您可以使用split轻松完成以下操作,例如:

input = "MISSISSIPPI,P"

word, char = input.split(",")

substrings = word.split(char)

output = substrings[0]

print(output)

print(substrings)

这是基本的;剩下的你应该能自己搞清楚

1。你知道吗

string = "MISSISSIPPI"
index = string.find(string, 'P')
result = string[:index]

2。你知道吗

string = "MISSISSIPPI"
string.partition('P')

你为什么要进口稀土?你可以用回复sub

import re

word=input("Add word: ")
m=input("Add char:  ")

result = re.sub('[{0}{1}]'.format(m.upper(), m.lower()), '', word)
print result

相关问题 更多 >