【问题标题】:Replace a name in a string in Python在 Python 中替换字符串中的名称
【发布时间】:2013-02-17 16:33:27
【问题描述】:

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

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

所以我只需要帮助让程序读取i in range 部分用我的名字而不是 Alice。

谢谢。

【问题讨论】:

  • 你正在研究什么编程语言??
  • 您将需要发布split_alice 数组和replace_alice() 函数。我们不能为你写那个,因为它会完全完成你的任务。如果您付出了扎实的努力,我们很乐意为您遇到困难的任务提供帮助。尽管如此,我们不太可能给出完整的答案。

标签: python string replace


【解决方案1】:

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

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

另外,如果您对任何事情有任何疑问,请使用help()
就像你的情况一样:

>>> 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
猜你喜欢
  • 2011-02-17
  • 2021-09-12
  • 1970-01-01
  • 2020-10-21
  • 2012-04-23
  • 2014-07-08
  • 1970-01-01
  • 2021-05-21
  • 2019-10-01
相关资源
最近更新 更多