在 Python 中替换字符串中的名称 [英] Replace a name in a string in Python

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

问题描述

我正在处理一项任务,我需要用我的名字替换 Alice.这是程序,

I'm working on a assignment and I need to replace Alice with my name. Here is the program,

for i in range(10):
    print(i)
    print(split_alice[i]).replace_alice("Alice","Alex")

所以我只需要帮助让程序使用我的名字而不是 Alice 读取范围部分的 i.

So I just need help to make the program read the i in range part with my name instead of Alice.

谢谢.

推荐答案

只需在字符串上使用 replace() 方法..
像这样

Just use replace() method on strings..
Like this

>>> mystr = 'My name is Alice'
>>> mystr.replace('Alice','Alex')
'My name is Alex'

另外,如果你有任何疑问,你应该使用help().
就像你的情况:

Also, if you have any doubts about anything, you should use help().
Like in your case:

>>> help(type(mystr))
Help on class str in module __builtin__:

class str(basestring)
 |  str(object) -> string
...
...
 |  replace(...)
 |      S.replace(old, new[, count]) -> string
 |      
 |      Return a copy of string S with all occurrences of substring
 |      old replaced by new.  If the optional argument count is
 |      given, only the first count occurrences are replaced.
 |  
...
...
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

这篇关于在 Python 中替换字符串中的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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