Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中,如何从字符串数组的偏移量中去掉前导空格?_Python_String_Removing Whitespace - Fatal编程技术网

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

在Python中,如何从字符串数组的偏移量中去掉前导空格?,python,string,removing-whitespace,Python,String,Removing Whitespace,我是Python新手,但我有一个简单的问题。我知道我可以使用lstrip()从字符串中去掉前导空格/制表符。但假设我有一个字符串str: str = '+ 12 3' 我希望结果是 '+12 3' 我希望通过在原始字符串的子字符串上调用lstrip来实现这一点: str[1:] = str[1:].lstrip() 但我得到了以下错误: Traceback (most recent call last): File "ex.py", line 51, in <mod

我是Python新手,但我有一个简单的问题。我知道我可以使用lstrip()从字符串中去掉前导空格/制表符。但假设我有一个字符串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
回溯(最近一次呼叫最后一次):
文件“ex.py”,第51行,在
打印(解决方案().myAtoi('12 3'))
myAtoi中的文件“ex.py”,第35行
str[x:]=str[x:].lstrip()
TypeError:“str”对象不支持项分配
有没有办法使用lstrip()实现这一点?或者我应该研究另一种方法吗

作为记录,这只是一个leetcode实践问题,我正试图用Python编写它来教自己——一些朋友说它值得学习


谢谢D

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

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

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

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

您可以使用正则表达式:

import re

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

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

(?您可以使用正则表达式:

import re

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

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

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

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

由于您是新成员,您应该知道Python字符串是不可变的,因此会出现错误。因为您是新成员,您应该知道Python字符串是不可变的,因此会出现错误。啊,很好,我也准备在我的答案中添加正则表达式解决方案,但这个问题仍然存在es cleaner.+1Ah,很好,我也准备在我的答案中添加正则表达式解决方案,但是这个更干净。+1Congrats on 10k!@cᴏʟᴅsᴘᴇᴇᴅ 很抱歉回来这么晚。上床睡觉了。不过这是早上的一个惊喜;-)谢谢!祝贺10公里!@cᴏʟᴅsᴘᴇᴇᴅ 很抱歉回来这么晚。去睡觉了。不过这是早上的一个惊喜;-)谢谢!