Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 比较和替换列表中的元素_Python - Fatal编程技术网

Python 比较和替换列表中的元素

Python 比较和替换列表中的元素,python,Python,我有一本字典:- dict= { 'b' : 'bob' , 'c' : 'code' , 'd' : 'do'} import re def convert(str) data=list(str.replace(' ','')) for dat in data print dat # this gives an output as # b # c # d # Here I want to compare each character(b,c,d) with the key

我有一本字典:-

   dict= { 'b' : 'bob' , 'c' : 'code' , 'd' : 'do'}
import re
def convert(str)
 data=list(str.replace(' ',''))
 for dat in data
 print dat
 # this gives an output as
 # b
 # c
 # d
 # Here I want to compare each character(b,c,d) with the key in my dict{} dictionary
 # and if there is a match(dict has 'b':'bob') then I want to replace the character with the 
 # dictionary value.
 # In summary i want to convert string bcd to bobcodedo.


if __name__== "__main__":
 sam('bcd')

总之,我想将字符串bcd转换为bobcodedo。

不要命名你的
字典
dict
string
str
,等等

In [12]:

D={ 'b' : 'bob' , 'c' : 'code' , 'd' : 'do'}
S='bcd'
In [13]:

''.join(map(D.get,S))
Out[13]:
'bobcodedo'
要扩展到第二个问题:

In [15]:

''.join(map(lambda x: D.get(x, ''),'bcdefg'))
Out[15]:
'bobcodedo'
In [16]:

''.join(map(lambda x: D.get(x, x),'bcdefg'))
Out[16]:
'bobcodedoefg'
要回答您评论中的问题,请执行以下操作:

In [12]:

bad_str='|xyz'
in_str1='acdefggt'
in_str2='asxsttgm'
In [13]:

set(bad_str).intersection(in_str2)
Out[13]:
{'x'}
In [14]:

if len(set(bad_str).intersection(in_str1))==0:
    print 'do someting'
else:
    print 'Abort!'
do someting

谢谢但是如果我有字符串s='bcdefg',这就不起作用,因为我不想在字典中定义e,f,g。如何仅更改bcd并保持efg不变?另外,如果我在字符串='bcd | efg'之间发现一个字符说“|”,我想抛出一个错误怎么办。在这个字符串中,当我找到“|”时,我想抛出一条异常消息——“停止解析”。如何做到这一点?这里应该使用reg ex吗?