简体   繁体   English

如何使用正则表达式用 * 替换所有字符

[英]How to replace all the characters with * using Regular Expression

I am having a text like我有一个像

s = bluesky

I want to get it as s = ******* (equal no of * as no of characters)我想把它作为s = ******* (等于没有 * 作为没有字符)

I am searching for a regular expression for Python.我正在寻找 Python 的正则表达式。

Edit 1 :编辑1:

b = '*'*len(s)

How can we do it in Django Template?我们如何在 Django 模板中做到这一点?

You don't need a regex for this:您不需要正则表达式:

s = 'bluesky'
b = '*'*len(s)
print b

output :输出:

>>> s = 'bluesky'
>>> b = '*'*len(s)
>>> print b
*******

No need for regexp, just text.replace('bluesky','*'*len('bluesky'))不需要正则表达式,只需text.replace('bluesky','*'*len('bluesky'))

eg:例如:

>>> text = "s = bluesky"
>>> text.replace('bluesky','*'*len('bluesky'))
's = *******'

How can we do it in Django Template我们如何在 Django 模板中做到这一点

In a Django template?在 Django 模板中? Dead easy.容易死。

{% for char in s %}*{% endfor %}

Where s is the template variable whose value is bluesky .其中s是模板变量,其值为bluesky

>>> import re
>>> re.sub("(\w+)\s*=\s*(\w+)", lambda m: "%s = %s" % (m.group(1), '*'*len(m.group(2))), "s = bluesky")
's = *******'
>>> re.sub("(\w+)\s*=\s*(\w+)", lambda m: "%s = %s" % (m.group(1), '*'*len(m.group(2))), "cat=dog")
'cat = ***'

Assuming your string is literally s = bluesky假设你的字符串字面上是s = bluesky

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

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