簡體   English   中英

在Python中替換字符串中的名稱

[英]Replace a name in a string in Python

我正在做作業,需要用我的名字代替Alice。 這是程序,

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

因此,我只需要幫助使程序使用我的名字而不是Alice讀取范圍內的i

謝謝。

只需在字符串上使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM