Python将字符串用特定字符分割并前面加序号
Python将字符串用特定字符分割并前面加序号,今天项目中就遇到,看着不难,得花点时间搞出来急用啊,在网上找了一圈,没发现有完整流程的文章。所以就搞出来并写了这个文章。仅供大家学习和项目上用。
第一步,应用背景
有这么一个字符串,有多个店名,想以店名分割并加上换行和序号,这样看起来字符串更加结构化,就取出来一个举例。
字符串
m_n = '''店名:huahuadebaby
邮箱:ak3097150480@163.com
ID:A36BJDGOVPQHNP
店名:shanxiyongganganggang
邮箱:shuigua7593@163.com
ID:A2A6KCSCLMCS0V
店名:SIXNITRS
邮箱:i15249615568@163.com
ID:A1GVT3U4OZT1Y9'''
想要达到的效果
1. 店名:huahuadebaby
邮箱:ak3097150480@163.com
ID:A36BJDGOVPQHNP
2. 店名:shanxiyongganganggang
邮箱:shuigua7593@163.com
ID:A2A6KCSCLMCS0V
3. 店名:SIXNITRS
邮箱:i15249615568@163.com
ID:A1GVT3U4OZT1Y9
第二步、直接上代码
m_n = '''店名:huahuadebaby
邮箱:ak3097150480@163.com
ID:A36BJDGOVPQHNP
店名:shanxiyongganganggang
邮箱:shuigua7593@163.com
ID:A2A6KCSCLMCS0V
店名:SIXNITRS
邮箱:i15249615568@163.com
ID:A1GVT3U4OZT1Y9'''
m_n_list = m_n.split("店名")
m_n_list.pop(0)
# print(m_n_list)
char_to_add = "店名"
new_list = [char_to_add + element for element in m_n_list]
# 使用例子
#strings = ["Apple", "Banana", "Cherry"]
def add_number_before_string(string_list, start_number=1):
formatted_strings = [(f"{i}. {s}") for i, s in enumerate(string_list, start=start_number)]
return formatted_strings
numbered_strings = add_number_before_string(new_list)
huanhang = "\n"
new_list = [huanhang + element for element in numbered_strings]
# print(new_list)
for s in new_list:
print(s)
new_str = ''.join(new_list)
print(new_str)
第三步、运行结果
1. 店名:huahuadebaby
邮箱:ak3097150480@163.com
ID:A36BJDGOVPQHNP
2. 店名:shanxiyongganganggang
邮箱:shuigua7593@163.com
ID:A2A6KCSCLMCS0V
3. 店名:SIXNITRS
邮箱:i15249615568@163.com
ID:A1GVT3U4OZT1Y9