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.
Asked
Active
Viewed 690 times
0
-
2`str.strip` might be what you want. – LeopardShark Apr 09 '22 at 18:30
-
See the answer here: https://stackoverflow.com/questions/8270092/remove-all-whitespace-in-a-string – baldwibr Apr 09 '22 at 18:32
-
That is a valid way to remove them, but I want to identify if they are there, and only strip the ones after visible characters. – solar515 Apr 09 '22 at 18:34
-
you can use pythons inbuilt string class specific `string.startswith()` and `string.endswith()` functions that return booloean – Bijay Regmi Apr 09 '22 at 18:42
-
`if mystring.startswith(' ') or mystring.endswith(' ')` – John Gordon Apr 09 '22 at 18:52
-
Alright it seems to work, thanks. – solar515 Apr 09 '22 at 19:01
-
Why do you need to check if they are there? `strip` will only remove leading and trailing spaces. If they are not there - nothing will happen... – Tomerikoo Apr 10 '22 at 05:31
4 Answers
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
.

ThatOneAmazingPanda
- 302
- 4
- 13
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