【问题标题】:Replacing The Tab Character In A String替换字符串中的制表符
【发布时间】:2023-01-07 18:39:05
【问题描述】:

假设我有一个这样的字符串:
a = a = "\t\t\t\t"
如果我打印出字符串中 "\t" 的计数,则输出如下:
print(a.count("\t")) == output = 4\ 如果我想在该字符串中的任何给定位置替换 "\t",我该怎么做?
前任:
a.replace("\t", "a") #replacing the (first occurrence?) of "\t?
print(a.count("\t")) == output = 3

然而"\t" 没有被 "a" 取代,因此 "\t" 计数仍然是 4。我有办法做到这一点吗?最好替换字符串中出现的任何给定的"\t"

【问题讨论】:

  • 请注意,“替换”会返回一个新的修改后的字符串,并且不会更改原始字符串。

标签: python replace count tabs character


【解决方案1】:

您可以使用正则表达式。这是另一种通过特定模式替换所有事件的方法

【讨论】:

    【解决方案2】:

    尝试使用expandtabs,比如text = text.expandtabs(tabsize=4)

    【讨论】:

      【解决方案3】:

      正如@Michael Butscher 所说,str.replace() 返回一个完成替换的新字符串。默认情况下,所有匹配项都被替换。这应该这样做:

      b = a.replace("	", "a")
      print(b.count("	"))
      

      见:https://docs.python.org/3/library/stdtypes.html?highlight=str%20replace#str.replace

      【讨论】:

        猜你喜欢
        • 2012-04-26
        • 1970-01-01
        • 2021-05-22
        • 1970-01-01
        • 2013-05-01
        • 2017-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多