python-刷题--1、从字符串中删除子串 2、字符串循环右移n位

本文介绍两种Python方法来删除字符串中的指定子串,以及如何通过循环右移改变字符串的顺序。提供了实用的代码示例,包括一种高效的方法和一种传统方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、问题描述:从给定的字符串中删除指定的子字符串,例如将字符串“abcdefgh”中子串“cd”删除,并显示结果。

我的python实现:

#!-*-coding:utf-8-*-

import sys,os

def delete_substr_method1(in_str, in_substr):
  start_loc = in_str.find(in_substr)
  in_str, in_substr = list(in_str), list(in_substr)
  [len_str, len_substr] = len(in_str), len(in_substr)
  res_str = in_str[:start_loc]
  for i in range(start_loc + len_substr, len_str):
    res_str.append(in_str[i])
  res = ''.join(res_str)
  return res

def delete_substr_method2(in_str, in_substr):
  start_loc = in_str.find(in_substr)
  len_substr = len(in_substr)
  res_str = in_str[:start_loc] + in_str[start_loc + len_substr:]
  return res_str


if __name__ == "__main__":
  in_str = input("please input string:")
  in_substr = input("please input substring:")
  result = delete_substr_method2(in_str, in_substr)
  print(result)
  print("ok")

2、字符串循环右移n位。如abcdefg右移2位后为fgabcde.

#!-*-coding:utf-8-*-

#pythonic method
def circle_move_method1(input_str, k):
  l = len(input_str)
  return input_str[l - k:] + input_str[:l - k]

#traditional method, space complexity O(1),time complexity O(n)
def circle_move_method2(input_str, k):
  input_str = list(input_str)
  #l = len(input_str)
  #for i in range(k):
  #  ch = input_str[l - 1]
  #  for j in range(l-1,0,-1):
  #    input_str[j] = input_str[j - 1]
  #  input_str[0] = ch
  #return "".join(input_str)

  #another imply style about comment block
  for i in range(k):
    input_str.insert(0, input_str.pop())
  return "".join(input_str)





if __name__ == "__main__":
  input_str = input("please input:")
  n = int(input("input the move value:"))
  print(circle_move_method2(input_str, n))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值