试试
a = ' hello world'
a.strip()
【讨论】:
-
O(n), ***.com/a/27684660/17047120
-
这只从左右剥离。
Python 就地修剪和删除字符串中多余空格的方法答案
Python in-place way of trimming & removing extra whitespace from a stringPython 就地修剪和删除字符串中多余空格的方法正在寻找一种方法来从大型 python 字符串 (100MB+) 中删除多余的空格而不进行复制。尝试使用ctypes
,但似乎您必须将字符串转换为bytes
才能使ctypes.memmove
工作。
我需要一个函数 remove_extra_whitespaces
可以在 O(1) 内存中执行此操作
>> a = ' hello world'
>> a = remove_extra_whitespaces(a)
>> a == 'hello world'
True
我可以使用库或其他东西来完成这项任务吗?
【问题讨论】:
.strip()
删除前导和尾随空格,但不影响任何中间空格
标签: python ctypes
试试
a = ' hello world'
a.strip()
【讨论】: