如何用Python中的另一个字符串替换函数中的字符串? [英] How to replace a string in a function with another string in Python?

查看:65
本文介绍了如何用Python中的另一个字符串替换函数中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

<预><代码>>>>特别 = 'x'>>>random_function('你好,你好吗')'xxxxxx xxx xxx xxx'

我基本上想返回字符串:{(str) -> str}

我不断得到未定义的变量.

抱歉,这是我的第一篇文章.

解决方案

由于 Python 中的字符串是不可变的,因此每次使用 replace() 方法时都必须创建一个新字符串.每次调用 replace 还必须遍历整个字符串.这显然是低效的,尽管在这个规模上并不明显.

另一种方法是使用列表理解(docs教程) 循环通过字符串一次并创建新字符的列表.可以使用 isalnum() 方法作为仅替换字母数字字符的测试(即,保留空格、标点符号等不变).

最后一步是使用 join() 方法将字符连接到新字符串中.请注意,在这种情况下,我们使用空字符串 '' 将字符连接在一起,它们之间没有任何内容.如果我们使用 ' '.join(new_chars) 每个字符之间会有一个空格,或者如果我们使用 'abc'.join(new_chars) 那么字母 abc 将在每个字符之间.

<预><代码>>>>def random_function(字符串,替换):... new_chars = [替换 if char.isalnum() else char for char in string]...返回 ''.join(new_chars)...>>>random_function('你好,你好吗', 'x')'xxxxxx xxx xxx xxx'

当然,你应该给这个函数一个比 random_function()...

更合乎逻辑的名字

I want to do this:

>>> special = 'x'
>>> random_function('Hello how are you')
'xxxxx xxx xxx xxx'

I basically want to return the string: {(str) -> str}

I keep on getting variables undefined.

Sorry this is my first post.

解决方案

Since strings in Python are immutable, each time you use the replace() method a new string has to be created. Each call to replace also has to loop through the entire string. This is obviously inefficient, albeit not noticeable on this scale.

One alternate is to use a list comprehesion (docs, tutorial) to loop through the string once and create a list of the new characters. The isalnum() method can be used as a test to only replace alphanumeric characters (i.e., leave spaces, punctuation etc. untouched).

The final step is to use the join() method to join the characters together into the new string. Note in this case we use the empty string '' to join the characters together with nothing in between them. If we used ' '.join(new_chars) there would be a space between each character, or if we used 'abc'.join(new_chars) then the letters abc would be between each character.

>>> def random_function(string, replacement):
...     new_chars = [replacement if char.isalnum() else char for char in string]
...     return ''.join(new_chars)
...
>>> random_function('Hello how are you', 'x')
'xxxxx xxx xxx xxx'

Of course, you should probably give this function a more logical name than random_function()...

这篇关于如何用Python中的另一个字符串替换函数中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆