Home > Mobile >  How to check for spaces before or after a string in python
How to check for spaces before or after a string in python

Time:04-10

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.

CodePudding user response:

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.

CodePudding user response:

try this

var = "   abc   "

var.strip()

CodePudding user response:

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.

CodePudding user response:

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
  • Related