Python中的下一行字符串的子字符串

Python中的下一行字符串的子字符串,python,Python,我需要Python方面的帮助,我有一个如下设置的字符串: string= “第1类 这是第一类 类别2 这是第二类“ 我想做的是提取与实际类别相关的字符串。例如,我想得到“Category 1”的值,我应该得到“This is the first Category”的值。听起来你想使用一个字典,其中“Category1”是键,“This is the first Category”的值 或者,您可以使用string.split(“\n”)拆分字符串,然后搜索“Category1”,并使用其位置

我需要Python方面的帮助,我有一个如下设置的字符串:

string=
“第1类
这是第一类 类别2
这是第二类“

我想做的是提取与实际类别相关的字符串。例如,我想得到“Category 1”的值,我应该得到“This is the first Category”的值。

听起来你想使用一个字典,其中“Category1”是键,“This is the first Category”的值

或者,您可以使用string.split(“\n”)拆分字符串,然后搜索“Category1”,并使用其位置调用后面的字符串


取决于您试图实现的目标。

听起来您想使用以“Category1”为键和“This is the first category”值的词典

text = """Category 1
This is the first category

Category 2
This is the second category"""

# list of tuples
out1 = [tuple(t.split("\n")) for t in text.split("\n\n")]

# list of dict
out2 = [{"cat": t.split("\n")[0],
         "val": t.split("\n")[1]}
           for t in text.split("\n\n")]

# dict
out3 = dict(out1)
或者,您可以使用string.split(“\n”)拆分字符串,然后搜索“Category1”,并使用其位置调用后面的字符串

这取决于你想要达到的目标

text = """Category 1
This is the first category

Category 2
This is the second category"""

# list of tuples
out1 = [tuple(t.split("\n")) for t in text.split("\n\n")]

# list of dict
out2 = [{"cat": t.split("\n")[0],
         "val": t.split("\n")[1]}
           for t in text.split("\n\n")]

# dict
out3 = dict(out1)
选择你需要的表格


选择您需要的表单。

请显示您迄今为止尝试过的代码……您想过使用字典吗?string={“category1”:“message”}请显示您迄今为止尝试过的代码……您想过使用字典吗?string={“category1”:“message”}这是问题的一半。你应该把它转换成一个dict,然后它就可以做他想做的事了。这是问题的一半。你应该把它转换成一个dict,然后它就可以做他想做的事情了。