You want to replace it, not strip it:
s = s.replace(',', '')
Answer from eumiro on Stack OverflowYou want to replace it, not strip it:
s = s.replace(',', '')
Use replace method of strings not strip:
s = s.replace(',','')
An example:
>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True
regex in Python to remove commas and spaces - Stack Overflow
How to remove spaces after comma in python? - Stack Overflow
how to remove a space before a comma?
pandas - Remove space between string after comma in python dataframe column - Stack Overflow
Use list comprehension -- simpler, and just as easy to read as a for loop.
my_string = "blah, lots , of , spaces, here "
result = [x.strip() for x in my_string.split(',')]
# result is ["blah", "lots", "of", "spaces", "here"]
See: Python docs on List Comprehension
A good 2 second explanation of list comprehension.
I came to add:
map(str.strip, string.split(','))
but saw it had already been mentioned by Jason Orendorff in a comment.
Reading Glenn Maynard's comment on the same answer suggesting list comprehensions over map I started to wonder why. I assumed he meant for performance reasons, but of course he might have meant for stylistic reasons, or something else (Glenn?).
So a quick (possibly flawed?) test on my box (Python 2.6.5 on Ubuntu 10.04) applying the three methods in a loop revealed:
$ time ./list_comprehension.py # [word.strip() for word in string.split(',')]
real 0m22.876s
$ time ./map_with_lambda.py # map(lambda s: s.strip(), string.split(','))
real 0m25.736s
$ time ./map_with_str.strip.py # map(str.strip, string.split(','))
real 0m19.428s
making map(str.strip, string.split(',')) the winner, although it seems they are all in the same ballpark.
Certainly though map (with or without a lambda) should not necessarily be ruled out for performance reasons, and for me it is at least as clear as a list comprehension.
you can use the split to create an array and filter len < 1 array
import re
s='word1 , word2 , word3, '
r=re.split("[^a-zA-Z\d]+",s)
ans=','.join([ i for i in r if len(i) > 0 ])
How about adding the following sentence to the end your program:
re.sub(',+$','', test_string)
which can remove the comma at the end of string
You can use replace() in your string
For example:
your_string.replace(", ", ",")
Where according to your question only the ", " (comma followed by space) is replaced by "," (comma).
This is due to your print statement. What you can do is first assign it to a variable, replace the spaces and then print it. The replace and print can be combined since replace returns the new string. So basically:
output = f"{integer_list[0:middle_value]}-[{integer_list[middle_value]}]-{integer_list[middle_value+1:]}"
print(output.replace(" ", "")
Hi :D
TOTAL noob here.
How to remove a space before a comma? For example here:
name=input("wuts ur name? ")
print("holy shit", name, ",", "your name has", name.lower().count("a"), "times the letter a!")So for example, if I input "Alexandra", it'll return:
holy shit Alexandra , your name has 3 times the letter a!
but as you can see, there is a space before the comma... how do I remove it? I tried several different things and searched on the internet too, but somehow couldn't find how welp XD
Thanks <3
It is advisable to use the regular expression ,\s+, which allows you to capture several consecutive whitespace characters after a comma, as in washington, harvard
df = pd.DataFrame({'ID': [1, 2], 'Col': ['new york, london school of economics, america',
'california & washington, harvard university, america']}).set_index('ID')
df.Col = df.Col.str.replace(r',\s+', ',', regex=True)
print(df)
Col
ID
1 new york,london school of economics,america
2 california & washington,harvard university,ame...
If you mention the axis it will be solved
df.apply(lambda x: x.str.replace(', ',',',regex=True),axis=1)
string.replace(" ,",",")
You can use the replace method to substitute " ," with "," and then you have what you want.
Although, with your example, just do:
print(contact.lastname+",",contact.firstname+",",contact.email+",",contact.phone)
When you do print(v,w) you automatically add a space. So if you do print(v,",",w) you have the space you try to get rid of. If, instead, you do print(v+",") then you have no space between the text in v and the comma.
You can use string format :
print(f"{contact.lastname},{contact.firstname},{contact.email},{contact.phone}")
Or if you want to keep multiple parameters in the print funciton, use the sep (separator) parameter :
print(a, b, c, sep=',')
I have a string that consists of something like:
my_string = 'Now is the time, , for all good men, , ,to come to the aid,, of their party'
...and I want to keep only a single comma for each repeating set of commas:
result = 'Now is the time, for all good men, to come to the aid, of their party'
I've looked a numerous methods to remove sequential characters, but 1) these are not sequential (may have one or more blanks between them); and 2) I only want to remove the extra commas and not other repeating characters that might appear in the string.
Any help would be greatly appreciated.
in python 3.6 you could use fstrings which are well readable and slightly faster than the other format-methods :
print(f'Hello {fn} {ln}!')
It's a stupid question, but I have to know why it's adding this random space after a comma.
The default setting of print is such that comma adds whitespace after it.
One way of removing the space before ! here is doing :
print('Hello,',fn, ln, end='')
print('!')
Out : Hello, First Last!
Here the end= specifies what should be printed upon end of print() statement instead of the default newline.
Another far more easier method is just to concatenate the string. ie,
print('Hello,',fn, ln + '!')
Im supposed to create a coding program that takes a cypher as an input( written in this format: a,H b,j c,6 d,I e,2 f,R where a pair is separated by comma and the pairs separated by space).
My approach was to transform the cypher into a list of lists and then iterate through the text replacing the letters and numbers in the text.
How can i do this?