简体   繁体   中英

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

I'm new to Python, but I had a simple question. I know that I can use lstrip() to strip leading whitespaces/tabs from a string. But lets say I have a string str:

str = '+        12  3' 

I want the result to be

'+12 3'

I wanted to achieve this by calling lstrip on a substring of the original string:

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

But I get the following error:

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

Is there a way to achieve this using lstrip()? Or should I look into another way of doing this?

For the record, this is just a leetcode practice problem, and I'm attempting to write it in Python to teach myself - some friends say its worth learning

Thanks! :D

You can call str.lstrip on the part of the string before the + , then concatenate the first character back:

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

You can use regular expressions:

import re

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

Output:

'+12  3'

Explanation:

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

str is an immutable type. You cannot change the existing string in place. You can build a new string and reassign the variable handle (by name). Christian already gave you the details of building the string you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM