繁体   English   中英

如何正确使用替换方法?

[英]How do you use the replace method properly?

phone_numbers = {"John Smith": "+37682929928", "Marry Simpsons": "+423998200919"}

遍历 phone_numbers 值并在每个循环中打印出电话号码,但使用 00 而不是 +。 换句话说,你的代码应该是 output: 0037682929928 00423998200919

new_phonenu=[]
for num in phone_numbers:
    new_phonenu = str.replace("+","00")
    new_phonenu.append(str)

使用单行 for 循环迭代并非常快速地对列表中的每个元素执行操作。

phone_numbers = {"John Smith": "+37682929928", "Marry Simpsons": "+423998200919"}

new_phonenu = [num.replace('+','00') for num in phone_numbers.values()]

print(*new_phonenu)

Output:

0037682929928 00423998200919

编辑:如果要包含密钥,请使用

phone_numbers = {"John Smith": "+37682929928", "Marry Simpsons": "+423998200919"}
new_phonenu = {k:num.replace('+','00') for k,num in phone_numbers.items()}
print(new_phonenu)

Pythonic 紧凑方式(保持非以加号开头):

new_phone_numbers = {p:('00'+n[1:] if n[0]=='+' else n) for p,n in phone_numbers.items()}

Pythonic 紧凑方式(不保留非以加号开头的数字):

new_phone_numbers = {p:'00'+n[1:] for p,n in phone_numbers.items() if n[0]=='+'}

更经典的方式 - 如果要包含不符合不以+开头的标准的数字,请取消注释最后两行:

new_phone_numbers = {}
for p in phone_numbers:
  t = phone_numbers[p].strip() # trim whitespaces at begging and end
  if t[0]=='+':
    new_phone_numbers[p]='00'+t[1:]
  #else:
    #new_phone_numbers[p]=t

中间+是有意保留的,只有在开始时才改变。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM