0

How can I find if there are spaces placed before the continuous string I have? For example: 1a2f3adfs3j With this string I want to identify if there are spaces before and after it, then remove them.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
solar515
  • 23
  • 5

4 Answers4

3

If you actually have interest in detecting the presence of these spaces you can check by taking advantage of the ability to slice strings.

s = " abc "
assert(s[0] == " ") # first char
assert(s[-1] == " ") # last char

But there are other ways:

assert(s.startswith(" "))
assert(s.endswith(" "))
# or
first, *_, last = s
assert(first == " ")
assert(last == " ")

You could also check both at the same time:

assert(s[::len(s)-1] == "  ")
# or
assert(s[0] + s[-1] == "  ")

Otherwise, as others pointed out. str.strip is likely what you're after. It will remove leading and trailing whitespace, but leave any within the text.

theherk
  • 6,954
  • 3
  • 27
  • 52
  • as a small second question relating to this but not enough to make a post, how can I remove the spaces outside the text, but keep the ones inside the characters? Sorry – solar515 Apr 09 '22 at 18:41
  • I'm happy to help further, but I don't understand your question? If you mean remove the spaces preceding non-whitespace characters and spaces following the last non-whitespace character, `strip` is the way to go. If you mean something else, let me know. – theherk Apr 09 '22 at 18:45
  • For example `assert(" a b ".strip() == "a b")`. Notice it left the space that was neither leading nor trailing. – theherk Apr 09 '22 at 18:46
1

To actually see if you have spaces, you could use:

s = " abcd1234 "
print(s[0] == " ", s[-1] == " ")

Or another way is to see if it startswith or endswith a space:

print(s.startswith(" "), s.endswith(" "))

To remove the spaces:

s = s.strip()

should do and remove the spaces and assign it to s.

0

try this

var = "   abc   "

var.strip()
Nikappa_
  • 127
  • 4
0

What about

>>> var = ' 1a2f3adfs3j '
>>> var == f' {var[1:-1]} '
True

which approach is not space-specific. e.g

>>> var = '__1a2f3adfs3j__'
>>> var == f'__{var[2:-2]}__'
True
keepAlive
  • 6,369
  • 5
  • 24
  • 39