简体   繁体   English

str.replace()方法如何工作?

[英]How does str.replace() method work?

I have this input: 我有这个输入:

'0472/91.39.17'

I want to replace my input with '1234567890' one by one like this: 我想像这样用'1234567890'一一替换我的输入:

'1234/56.78.90'

But my outcome is 但是我的结果是

0472/91.09.17

Here's my code 这是我的代码

phone = '0472/91.39.17'
repl = 1234567890

for i in phone:
    if i.isdigit():
        for j in str(repl):
            x = phone.replace(i, j)
        print(x)

What is the proper way to do this? 正确的方法是什么?

You can turn repl into an iterator and use a generator expression to replace any value in phone with the next value in the repl iter if the original value is a digit. 如果原始值是数字,则可以将repl转换为迭代器,并使用生成器表达式将phone任何值替换为repl iter中的下一个值。 Re-combine that together with ''.join to get a string as a result, and Bob's your uncle. 将其与''.join一起重新组合以得到一个字符串,结果鲍勃是你的叔叔。

repliter = iter(str(repl))

result = ''.join(next(repliter) if c.isdigit() else c for c in phone)
# the ternary expression here evaluates to:
# if c.isdigit():
#     next(repliter)
# else:
#     c

Note that this will crash with a StopIteration error if your phone number contains more than 10 digits, so consider using itertools.cycle for repliter instead. 请注意,如果您的电话号码包含10位以上的数字,这将因StopIteration错误而崩溃,因此请考虑改用itertools.cycle进行repliter

import itertools

repliter = itertools.cycle(str(repl)) # 1 2 3 4 5 6 7 8 9 0 1 2 3 ...

I was thinking you could use itertools count with modulus for numbers higher than 10. 我在想您可以使用itertools count和大于10的模数。

from itertools import count

c = count(0) # start number
phone = '0472/91.39.17'

''.join(str(next(c) % 10) if item.isdigit() else item for item in phone)

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

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