python - 如何用另一个字符串的前两个字符替换字符串的前两个字符?

标签 python string replace

我知道这个替换字符问题可能已经提出并且我已经检查过了,但他们仍然没有回答我的问题。我也是 python 的新手,所以我的理解并不是那么惊人。

def stringMix():
    MixA = print (userStringA.replace([0:2],userStringB[0:2]))
    MixB = print (userStringB.replace([0:2],userStringB[0:2]))

userStringA = input("Please enter a string consisting of over two characters ")
userStringB = input("Please enter a second string consisting of over two characters ")

print (userStringA)
print (userStringB)

print (MixA, MixB)

到目前为止,这是我的代码,但是当我运行它时,它会出现突出显示冒号的语法错误。我只是想用 userStringB 的前两个字符替换 userStringA 的前两个字符,反之亦然。

最佳答案

您没有正确使用方法调用。即,您将 stringMix 定义为函数,但使用的变量超出了函数的范围。我想你要做的是:

def stringMix(a,b):
  print (a.replace([0:2]b[0:2]))
  print (b.replace([0:2],a[0:2]))

userStringA = input("Please enter a string consisting of over two characters ")
userStringB = input("Please enter a second string consisting of over two characters ")

print (userStringA)
print (userStringB)

stringMix(userStringA,userStringB)

但是,正如之前的答案和评论所暗示的那样,str.replace 并不是执行此操作的真正方法。你应该这样做:

def stringMix(a,b):
  print (a[0:2]+b[2:])
  print (b[0:2]+a[2:])

利用字符串切片和连接

关于python - 如何用另一个字符串的前两个字符替换字符串的前两个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33221677/

相关文章:

lua - Lua中如何去除字符串中的空格?

python - Scrapy 导入错误

python - 如何在Python中加载Matlab的结构体(用v7.3保存)

java - 如何在 Java 中比较字符串?

python - 如何在不转换为列表的情况下替换 python 字符串中特定位置的字母?

Excel vba最后查找和替换

python - 带有变量 sig figs 的 sig fig 格式化显示

python - While循环不断循环Python 3.3

Ruby #split ("") 与字符串上的#chars

python - 从 str 派生的类的构造函数,具有不同的签名