如何在Python中将字符串中的制表符扩展到多个空格?
Python有效地处理字符串之间的空格。在本文中,我们将讨论在字符串中提供空格的方法,当我们不确定需要多少空格时。
阅读更多:Python 教程
使用字符串expandtabs()方法
Python中的一个内置方法称为String expandtabs()用于处理字符串中的空格。Python中的expandtabs()方法创建了一个字符串副本,其中所有制表符“\ t”直到下一个多个tabsize参数被替换为空格字符。
在某些情况下,可能需要定义字符串中留下多少空格,但具体数量取决于情况。
在这些情况下不断调整字符串是一项费力的工作。因此,Python库中的“expandtabs()”方法定义应在“ \ t”符号替换之前添加多少空格。
语法
使用expandtabs()的语法如下 –
string.expandtabs(size_of_tab)
其中,
size_of_tab_是替换\t的空格字符大小。默认值为8。
返回值
在选项卡大小参数的下一个倍数之前,在返回的字符串中将所有’\t’字符替换为空格字符。
示例
无需任何参数
在下面的示例中,我们不将任何参数传递给expandtabs()函数 –
string = "Expanding\ttabs\tin\tstring\tto\tmultiple\tspaces."
result = string.expandtabs()
print('The expanded string is:',result)
输出
上面的示例中使用了Python字符串expandtabs()函数,没有参数,即没有size。因此,在’\ t’的位置上使用默认大小8。
The expanded string is: Expanding tabs in string to multiple spaces.
示例
不同的参数
在下面的示例中,我们将不同的参数传递给expandtabs()函数 –
string = "Expanding\ttabs\tin\tstring\tto\tmultiple\tspaces."
result = string.expandtabs(6)
result1 = string.expandtabs(3)
result2 = string.expandtabs(2)
print('The expanded string is:',result)
print('The expanded string is:',result1)
print('The expanded string is:',result2)
输出
在上面的代码示例中,向Python字符串expandtabs()函数传递了大小= 6,大小= 3,大小= 2。因此,在整个字符串中使用了大小为6,3和2个单位的空格代替字符“\t”。
The expanded string is: Expanding tabs in string to multiple spaces.
The expanded string is: Expanding tabs in string to multiple spaces.
The expanded string is: Expanding tabs in string to multiple spaces.
在expandtabs()中的错误和异常
如果我们尝试将一个不是整数类型的值传递为参数,例如浮点数,Python字符串expandtabs()函数会引发TypeError异常。
因此,很明显,expandtabs()函数只接受整数类型的参数。以下是通过将非整数值作为参数传递的expantabs()方法的示例−
示例
string = "在字符串中\t扩展\t制表符\t为\t多个\t空格。"
result = string.expandtabs(6.2)
print('扩展后的字符串为:',result)
输出
在执行上述代码时会抛出以下错误−
Traceback (most recent call last):
File "main.py", line 2, in <module>
result = string.expandtabs(6.2)
TypeError: integer argument expected, got float
使用numpy.expandtabs()函数
Python Numpy模块中的numpy.char.expandtabs()函数执行与内置的expandtabs()函数相同的功能。
如果用户想要更准确,也可以向numpy.char.expandtabs()函数传递一个数组参数以及空格的大小。
语法
以下是numpy.expandtabs()的语法−
numpy.char.expandtabs(array,size_of_tab)
其中,
- array 包括函数操作的元素。
-
size_of_tab(可选) 指定要提供的空格的大小,将制表符空格字符或”\t”替换为此可选参数。
示例
以下是numpy.expantabs()函数的示例−
import numpy
given_array = numpy.array("在字符串中\t扩展\t制表符\t为\t多个\t空格。")
result = numpy.char.expandtabs(given_array,16)
print('扩展后的字符串数组为:',result)
输出
以下是上述代码的输出−
扩展后的字符串数组为:在字符串中 扩展 制表符 为 多个 空格。
使用replace()方法
Python中的字符串类包含一个名为replace的方法。 它需要两个字符串作为输入:一个用于替换,另一个用于替换的内容。 它与字符串对象一起使用。
示例
以下是使用replace()方法将字符串中的制表符扩展为多个空格的示例−
string = "在字符串中扩展制表符为多个空格。"
result = string.replace('\t', '')
print( result)
输出
以下是上述代码的输出
在字符串中扩展制表符为多个空格。
使用re模块
正则表达式也可以使用Python的“re”模块来实现相同的结果。 要替换字符串中的字符,请使用函数re.sub(regex to replace, regex to replace with, string)。
示例
以下是使用re模块将字符串中的制表符扩展为多个空格的示例−
import re
string = "将字符串中的制表符扩展为多个空格。"
result = re.sub('\t', '',string)
print(result)
输出
以下是上述代码的输出结果−
将字符串中的制表符扩展为多个空格。