Why doesn't .strip() remove whitespaces? [duplicate] - python

This question already has answers here:
Remove all whitespace in a string
(14 answers)
Python String replace doesn't work [duplicate]
(1 answer)
Closed 1 year ago.
I have a function that begins like this:
def solve_eq(string1):
string1.strip(' ')
return string1
I'm inputting the string '1 + 2 * 3 ** 4' but the return statement is not stripping the spaces at all and I can't figure out why. I've even tried .replace() with no luck.

strip does not remove whitespace everywhere, only at the beginning and end. Try this:
def solve_eq(string1):
return string1.replace(' ', '')
This can also be achieved using regex:
import re
a_string = re.sub(' +', '', a_string)

strip doesn't change the original string since strings are immutable. Also, instead of string1.strip(' '), use string1.replace(' ', '') and set a return value to the new string or just return it.
Option 1:
def solve_eq(string1):
string1 = string1.replace(' ', '')
return string1
Option 2:
def solve_eq(string1):
return string1.replace(' ', '')

strip returns the stripped string; it does not modify the original string.

Related

How to check multiple consecutive spaces in a string with python? [duplicate]

This question already has answers here:
Python - Check multiple white spaces in string
(3 answers)
Closed 2 years ago.
I want to find multiple spaces in a string using python. How to check if multiple spaces exist in a string?
mystring = 'this is a test'
I have tried the below code but it does not work.
if bool(re.search(' +', ' ', mystring))==True:
# ....
The result must return True.
You can use split() if you give no delimiter it will consider space as delimiter. after split check the length.If the length is greater than one it has spaces.
mystring = 'this is a test'
if len(mystring.split()) > 1:
#do something
You can use the string.count() method:
If you want to check if multiple (more than one and no matter what their length) spaces exist the code is:
mystring.count(' ')>1
If you want to check if there is at least one consecutive space the code is:
mystring.count(' ')>=1
You can use re and compare the strings like this:
import re
mystring = 'this is a test'
new_str = re.sub(' +', ' ', mystring)
if mystring == new_str:
print('There are no multiple spaces')
else:
print('There are multiple spaces')
The syntax you use for re.search is wrong. It should be re.search(pattern, string, flags=0).
So, you can just do, searching for 2 or more spaces:
import re
def contains_multiple_spaces(s):
return bool(re.search(r' {2,}', s))
contains_multiple_spaces('no multiple spaces')
# False
contains_multiple_spaces('here are multiple spaces')
# True

Python : How to check if a variable is equal to '' '' [duplicate]

This question already has answers here:
Check if string contains only whitespace
(11 answers)
Closed 4 years ago.
I have a variable:
exchange_name = ''
Now I want to perform some operation based on checking if it is equal to an empty string.
So, I do:
if exchange_name == '':
# perform some operation
But how can I generalize the solution so that exchange_name can contain any number of spaces, e.g.:
exchange_name = ' '
or
exchange_name = ' '
Can anybody suggest an approach? Thanks in advance.
exchange_name.strip()==''
strip removes all empty spaces.
Try to use rstrip to remove spaces from begin and end of string.
if mytext.rstrip() == '':
do_it()

Python - First and last character in string must be alpha numeric, else delete [duplicate]

This question already has answers here:
How to remove non-alphanumeric characters at the beginning or end of a string
(5 answers)
Closed 6 years ago.
I am wondering how I can implement a string check, where I want to make sure that the first (&last) character of the string is alphanumeric. I am aware of the isalnum, but how do I use this to implement this check/substitution?
So, I have a string like so:
st="-jkkujkl-ghjkjhkj*"
and I would want back:
st="jkkujkl-ghjkjhkj"
Thanks..
Though not exactly what you want, but using str.strip should serve your purpose
import string
st.strip(string.punctuation)
Out[174]: 'jkkujkl-ghjkjhkj'
You could use regex like shown below:
import re
# \W is a set of all special chars, and also include '_'
# If you have elements in the set [\W_] at start and end, replace with ''
p = re.compile(r'^[\W_]+|[\W_]+$')
st="-jkkujkl-ghjkjhkj*"
print p.subn('', st)[0]
Output:
jkkujkl-ghjkjhkj
Edit:
If your special chars are in the set: !"#$%&\'()*+,-./:;<=>?#[\]^_`{|}~
#Abhijit's answer is much simpler and cleaner.
If you are not sure then this regex version is better.
You can use following two expressions:
st = re.sub('^\W*', '', st)
st = re.sub('\W*$', '', st)
This will strip all non alpha chars of the beginning and the end of the string, not just the first ones.
You could use a regular expression.
Something like this could work;
\w.+?\w
However I'm don't know how to do a regexp match in python..
hint 1: ord() can covert a letter to a character number
hint 2: alpha charterers are between 97 and 122 in ord()
hint 3: st[0] will return the first letter in string st[-1] will return the last
An exact answer to your question may be the following:
def stringCheck(astring):
firstChar = astring[0] if astring[0].isalnum() else ''
lastChar = astring[-1] if astring[-1].isalnum() else ''
return firstChar + astring[1:-1] + lastChar

Trying to remove white spaces in python .replace not working [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 6 years ago.
For some reason string.replace(" ", "") is not working.
Is there another way of removing white spaces from a string?
Why is .replace not working in this particular situation?
string = input('enter a string to see if its a palindrome: ')
string.replace(' ', '') # for some reason this is not working
# not sure why program will only work with no spaces
foo = []
bar = []
print(string)
for c in string:
foo.append(c)
bar.append(c)
bar.reverse()
if foo == bar:
print('the sentence you entered is a palindrome')
else:
print('the sentence you entered is not a palindrome')
replace() returns a new string, it doesn't modify the original. Try this instead:
string = string.replace(" ", "")

Having trouble adding a space after a period in a python string

I have to write a code to do 2 things:
Compress more than one occurrence of the space character into one.
Add a space after a period, if there isn't one.
For example:
input> This is weird.Indeed
output>This is weird. Indeed.
This is the code I wrote:
def correction(string):
list=[]
for i in string:
if i!=" ":
list.append(i)
elif i==" ":
k=i+1
if k==" ":
k=""
list.append(i)
s=' '.join(list)
return s
strn=input("Enter the string: ").split()
print (correction(strn))
This code takes any input by the user and removes all the extra spaces,but it's not adding the space after the period(I know why not,because of the split function it's taking the period and the next word with it as one word, I just can't figure how to fix it)
This is a code I found online:
import re
def correction2(string):
corstr = re.sub('\ +',' ',string)
final = re.sub('\.','. ',corstr)
return final
strn= ("This is as .Indeed")
print (correction2(strn))
The problem with this code is I can't take any input from the user. It is predefined in the program.
So can anyone suggest how to improve any of the two codes to do both the functions on ANY input by the user?
Is this what you desire?
import re
def corr(s):
return re.sub(r'\.(?! )', '. ', re.sub(r' +', ' ', s))
s = input("> ")
print(corr(s))
I've changed the regex to a lookahead pattern, take a look here.
Edit: explain Regex as requested in comment
re.sub() takes (at least) three arguments: The Regex search pattern, the replacement the matched pattern should be replaced with, and the string in which the replacement should be done.
What I'm doing here is two steps at once, I've been using the output of one function as input of another.
First, the inner re.sub(r' +', ' ', s) searches for multiple spaces (r' +') in s to replace them with single spaces. Then the outer re.sub(r'\.(?! )', '. ', ...) looks for periods without following space character to replace them with '. '. I'm using a negative lookahead pattern to match only sections, that don't match the specified lookahead pattern (a normal space character in this case). You may want to play around with this pattern, this may help understanding it better.
The r string prefix changes the string to a raw string where backslash-escaping is disabled. Unnecessary in this case, but it's a habit of mine to use raw strings with regular expressions.
For a more basic answer, without regex:
>>> def remove_doublespace(string):
... if ' ' not in string:
... return string
... return remove_doublespace(string.replace(' ',' '))
...
>>> remove_doublespace('hi there how are you.i am fine. '.replace('.', '. '))
'hi there how are you. i am fine. '
You try the following code:
>>> s = 'This is weird.Indeed'
>>> def correction(s):
res = re.sub('\s+$', '', re.sub('\s+', ' ', re.sub('\.', '. ', s)))
if res[-1] != '.':
res += '.'
return res
>>> print correction(s)
This is weird. Indeed.
>>> s=raw_input()
hee ss.dk
>>> s
'hee ss.dk'
>>> correction(s)
'hee ss. dk.'

Categories

Resources