替换字符串中的子串

通过一个简单的任务实现这样的一个任务: 当给定一个字符串,通过查询一个替换字典,将字符串中被标记的子字符串替换掉!

实现的方法如下:

 1 def expand(format, d, marker=‘"‘, safe=False):
 2     if safe:
 3         def lookup(w): return d.get(w, w.join(marker*2))
 4     else:
 5         def lookup(w): return d[w]
 6     parts = format.split(marker)
 7     parts[1::2] = map(lookup,parts[1::2])
 8     return ‘‘.join(parts)
 9
10 if __name__ == ‘__main__‘:
11     print expand(‘just "a" test‘, {‘a‘:‘one‘})

通过对特定的分隔符进行切片后,利用map函数进行列表的映射,将需要替换的子字符串进行替换。输出结果如下:

just one test.

时间: 2024-08-14 22:56:32

替换字符串中的子串的相关文章

《Python CookBook2》 第一章 文本 - 替换字符串中的子串

替换字符串中的子串 任务: 给定一个字符串,通过查询一个字符串替换字典,将字符串中被标记的子字符串替换掉. 解决方案: >>> import string >>> new_style = string.Template('this is $thing') #给substitute 方法传入一个字典参数并调用 >>> print new_style.substitute({'thing':5}) this is 5 >>> print

替换字符串中的空格

题目描述: 请实现一个函数,将一个字符串中的空格替换成"%20".例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy. 输入: 每个输入文件仅包含一组测试样例. 对于每组测试案例,输入一行代表要处理的字符串. 输出: 对应每个测试案例,出经过处理后的字符串. 样例输入: We Are Happy 样例输出: We%20Are%20Happy -------------------------------------------------

字符串-02. 删除字符串中的子串(20)

输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2. 输入格式: 输入在2行中分别给出不超过80个字符长度的.以回车结束的2个非空字符串,对应S1和S2. 输出格式: 在一行中输出删除字符串S1中出现的所有子串S2后的结果字符串. 输入样例: Tomcat is a male ccatat cat 输出样例: Tom is a male import java.util.Scanner; public class Main { public static

JavaScript替换字符串中最后一个字符

1.问题背景 在一个输入框中,限制字符串长度为12位.利用键盘输入一个数字,会将字符串中最后一位替换,比方:111111111111.再输入一个3,会显示111111111113 2.详细实现 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html x

spoj 694 求一个字符串中不同子串的个数

SPOJ Problem Set (classical) 694. Distinct Substrings Problem code: DISUBSTR Given a string, we need to find the total number of its distinct substrings. Input T- number of test cases. T<=20; Each test case consists of one string, whose length is <=

C++ 在字符串中插入子串+推断字符串是否由空格组成

// Example3.cpp : 定义控制台应用程序的入口点. #include "StdAfx.h" #include <string> #include <iostream> using namespace std; int main(void) { string str,str1,str2; int index; //推断截取的子串是否由blanks组成 str=" cjc is a master."; str1="cjc

删除字符串中的子串

输入2个字符串S1和S2,要求删除字符串S1中出现的所有子串S2,即结果字符串中不能包含S2. 输入格式: 输入在2行中分别给出不超过80个字符长度的.以回车结束的2个非空字符串,对应S1和S2. 输出格式: 在一行中输出删除字符串S1中出现的所有子串S2后的结果字符串. 输入样例: Tomcat is a male ccatat cat 输出样例: Tom is a male #include<stdio.h> #include<string.h> int main(){ cha

字符串中数字子串的求和

字符串中数字子串的求和 题目: 给定一个字符串str,求其中全部数字串所代表的数字之和. 要求: 1.忽略小数点字符,例如"A1.3",其中包含两个数字1和3. 2.如果紧贴数字子串的左侧出现字符'-',当连续出现次数为奇数时, 则数字视为负,连续出现的数量为偶数时,则数字视为正. 例如:"A-1BC--12",其中包含数字为-1和12. 例: str = "A1CD2E33" , 返回36 str = "A-1B--2C--D6E&q

08-在字符串中统计子串出现的次数

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace _05在字符串中统计子串出现的次数 { class Program { static void Main(string[] args) { int count = SubstringCount("qhwerzdfrefysasefh