如何从 Python 中的字符串数组的偏移量中去除前导空格?

How to strip leading whitespaces from an offset of a string array in Python?

我是 Python 的新手,但我有一个简单的问题。我知道我可以使用 lstrip() 从字符串中去除前导 whitespaces/tabs。但是假设我有一个字符串 str:

str = '+        12  3' 

我想要的结果是

'+12 3'

我想通过在原始字符串的子字符串上调用 lstrip 来实现:

str[1:] = str[1:].lstrip()

但我收到以下错误:

Traceback (most recent call last):
File "ex.py", line 51, in <module>
print(Solution().myAtoi('    12  3'))
File "ex.py", line 35, in myAtoi
str[x:] = str[x:].lstrip()
TypeError: 'str' object does not support item assignment

有没有办法使用 lstrip() 实现此目的?或者我应该研究另一种方法吗?

郑重声明,这只是一个leetcode练习题,我正在尝试写在Python中自学-有些朋友说值得学习

谢谢! :D

您可以在+之前的部分调用str.lstrip,然后将第一个字符连接回去:

>>> s = '+        12  3'
>>> s = s[0] + s[1:].lstrip()
>>> s
'+12  3'

您可以使用正则表达式:

import re

data = re.sub("(?<=\+)\s+", '', '+        12  3')

输出:

'+12  3'

解释:

(?<=\+) #is a positive look-behind
\s+ #will match all occurrences of white space unit a different character is spotted.

str 是不可变类型。您不能 更改现有字符串。您可以 构建一个新字符串并重新分配变量句柄(按名称)。 Christian 已经为您提供了构建所需字符串的详细信息。