Jor*_*ron 20 python string python-3.x
如何从特定索引替换字符串中的字符?例如,我想从字符串中获取中间字符,如abc,如果字符不等于用户指定的字符,那么我想替换它.
这样的事可能吗?
middle = ? # (I don't know how to get the middle of a string)
if str[middle] != char:
str[middle].replace('')
Run Code Online (Sandbox Code Playgroud)
ti7*_*ti7 24
由于字符串在Python中是不可变的,只需创建一个新字符串,其中包含所需索引处的值.
假设你有一个字符串s,也许吧s = "mystring"
您可以快速(并且显然)通过将其放置在原始"切片"之间来替换所需索引处的部分.
s = s[:index] + newstring + s[index + 1:]
Run Code Online (Sandbox Code Playgroud)
您可以通过将字符串长度除以2来找到中间位置 len(s)/2
如果你正在获得神秘输入,你应该注意处理超出预期范围的指数
def replacer(s, newstring, index, nofail=False):
# raise an error if index is outside of the string
if not nofail and index not in range(len(s)):
raise ValueError("index outside given string")
# if not erroring, but the index is still not in the correct range..
if index < 0: # add it to the beginning
return newstring + s
if index > len(s): # add it to the end
return s + newstring
# insert the new string between "slices" of the original
return s[:index] + newstring + s[index + 1:]
Run Code Online (Sandbox Code Playgroud)
这将起作用
replacer("mystring", "12", 4)
'myst12ing'
Run Code Online (Sandbox Code Playgroud)
Wil*_*sem 10
Python中的字符串是不可变的,这意味着您无法替换它们的一部分.
但是,您可以创建一个已修改的新字符串.请注意,这在语义上并不等效,因为不会更新对旧字符串的其他引用.
你可以编写一个函数:
def replace_str_index(text,index=0,replacement=''):
return '%s%s%s'%(text[:index],replacement,text[index+1:])
Run Code Online (Sandbox Code Playgroud)
然后例如用以下方法调用它:
new_string = replace_str_index(old_string,middle)
Run Code Online (Sandbox Code Playgroud)
如果您不提供替换,则新字符串将不包含您要删除的字符,您可以为其提供任意长度的字符串.
例如:
replace_str_index('hello?bye',5)
Run Code Online (Sandbox Code Playgroud)
会回来'hellobye'; 和:
replace_str_index('hello?bye',5,'good')
Run Code Online (Sandbox Code Playgroud)
会回来的'hellogoodbye'.
您不能替换字符串中的字母。将字符串转换为列表,替换字母,然后将其转换回字符串。
>>> s = list("Hello world")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[int(len(s) / 2)] = '-'
>>> s
['H', 'e', 'l', 'l', 'o', '-', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello-World'
Run Code Online (Sandbox Code Playgroud)
# Use slicing to extract those parts of the original string to be kept
s = s[:position] + replacement + s[position+length_of_replaced:]
# Example: replace 'sat' with 'slept'
text = "The cat sat on the mat"
text = text[:8] + "slept" + text[11:]
Run Code Online (Sandbox Code Playgroud)
I/P : 猫坐在垫子上
O/P : 猫睡在垫子上