-3

The objective is to remove a specified number of spaces from the beginning of a string, where the number of spaces at the start always exceed the required amount. The desired outcome is to obtain modified strings with only the specified number of spaces removed.

Here's an example to illustrate the problem:

text1 = "        Hello, world!"
text2 = "             Hello, world2!"
num_spaces_to_remove = 5
result1 = "   Hello, world!"
result2 = "        Hello, world2!"

In this scenario, text1 and text2 represent the original strings with varying numbers of spaces at the beginning. The goal is to remove exactly 5 spaces from each string, resulting in the modified strings result1 and result2, respectively.

My Current solution is something like this -

for c_line in commits_diffs_backport_context:
    if c_line.startswith(("+")):
        c_line = c_line.replace("+", "")
        commits_diffs_backportLines = commits_diffs_backportLines + c_line.replace(c_line[:leadingSpacesBac], "") + "\n"

Looking for a fastest solution. Thanks in advance.

joydeba
  • 778
  • 1
  • 9
  • 24
  • 4
    So, to be clear, if there were *6* spaces, would you still want to remove just 5? – user2357112 May 25 '23 at 16:05
  • 4
    What should the result be if `num_spaces_to_remove = 5` but `text` has only 2 (for example) spaces at the start? – slothrop May 25 '23 at 16:06
  • 1
    So if say `text = " Hello world"` (2 spaces at the beginning) and `num_spaces_to_remove = 5`, what would you want the result to be? – slothrop May 25 '23 at 16:17
  • num_spaces_to_remove is always < the spaces at the beginning. – joydeba May 25 '23 at 16:19
  • Minimum of 5 means 5 or more. It's unclear what is supposed to happen, if there are less than 5 spaces. Or did you mean maximum? – gre_gor May 25 '23 at 16:20
  • 1
    And what code are you using now, that doesn't have the desired performance? – gre_gor May 25 '23 at 16:21
  • 1
    @joydeba You should include concrete examples of before and after strings that cover all possible situations. EG 1) Less than 5 spaces, 2) exactly 5 spaces and 3) more than 5 spaces. And also do you need to detect strings with more than 5 spaces? – Peter M May 25 '23 at 16:21
  • Question updated. Thanks! – joydeba May 25 '23 at 16:32
  • 1
    Sounds like `text[num_spaces_to_remove:]` would do the job, assuming you know that there are enough leading spaces. – user2357112 May 26 '23 at 08:06
  • 1
    Those spaces just seem to be a red herring. You just want to slice off the first 5 characters, so this is a dupe of [How slicing in Python works](https://stackoverflow.com/q/509211). – gre_gor May 26 '23 at 18:11

1 Answers1

-4
def minus_blanks_from_start(b):
    a = '...........hello, world! '
    a = a[b:]
    return a

Use this replace '...'s with spaces

eg:

minus_blanks_from_start(4)

output:

.......hello, world! 
Upbeat25YT
  • 21
  • 4