免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5902 | 回复: 3

python replace 函数的用法 [复制链接]

论坛徽章:
5
程序设计版块每日发帖之星
日期:2016-04-15 06:20:00每日论坛发贴之星
日期:2016-04-15 06:20:0015-16赛季CBA联赛之八一
日期:2016-07-08 09:20:28操作系统版块每日发帖之星
日期:2016-08-03 06:20:002016科比退役纪念章
日期:2016-10-30 13:59:12
发表于 2018-07-18 18:10 |显示全部楼层
题库对应链接:http://codingbat.com/prob/p149524

问题:

给定非空字符串和int n,返回一个新字符串,其中索引n处的char已被删除。 n的值将是原始字符串中char的有效索引(即n将在0..len(str)-1的范围内)。


missing_char('kitten', 1) → 'ktten'
missing_char('kitten', 0) → 'itten'
missing_char('kitten', 4) → 'kittn'


答案:
我是这样写的一个函数:
def missing_char(str, n):
  if n in range(0,len(str)-1):
     str.replace(str[n],"")
     retrun str

我这里第四行做的是要用将str[n]这个字符删除掉。

提示我第四行 str.replace(str[n],"") 有语法错误,请问是哪里有问题?



论坛徽章:
1
午马
日期:2013-08-21 12:56:14
发表于 2018-07-23 13:59 |显示全部楼层
使用python3.6试了一下,没问题。另外,你的程序写错了,不能使用替换写。试试下标截取

论坛徽章:
0
发表于 2018-08-29 16:23 |显示全部楼层
def missing_char(s, i):
   return s[0:i]+s[i+1:]

string1="ABCDEFGHIJKLMN"
print missing_char(string1, 4)

ABCDFGHIJKLMN

论坛徽章:
0
发表于 2018-08-30 16:18 |显示全部楼层
replace(...)
    S.replace(old, new[, count]) -> str
   
    Return a copy of S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.
返回的是copy str

def missing_char(string, n):
  if n in range(0,len(string)-1):
     print(string[n], '', n)
     return string.replace(string[n], "", 1)

str = 'kitten'
print(missing_char(str, 3))
bash-3.2$ python3 rep.py
t  3
kiten
另外还有替换次数呢,重复的是都替换么? 仔细看replace函数的描述
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP