1

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

1
  • 3
    Since you are new, you should know that Python strings are immutable, hence the error. Commented Sep 1, 2017 at 21:38

3 Answers 3

3

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'
Sign up to request clarification or add additional context in comments.

2 Comments

Congrats on 10k!
@cᴏʟᴅsᴘᴇᴇᴅ Sorry for getting back so late. Went to bed. This was a nice surprise in the morning though ;-) Thanks!
2

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.

1 Comment

Ah, nice I was getting ready to add a regex solution to my answer as well, but this ones cleaner. +1
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.