remove unwanted space in between a string [duplicate] - python

This question already has answers here:
Is there a simple way to remove multiple spaces in a string?
(27 answers)
Closed 6 years ago.
I wanna know how to remove unwanted space in between a string. For example:
>>> a = "Hello world"
and i want to print it removing the extra middle spaces.
Hello world

This will work:
" ".join(a.split())
Without any arguments, a.split() will automatically split on whitespace and discard duplicates, the " ".join() joins the resulting list into one string.

Regular expressions also work
>>> import re
>>> re.sub(r'\s+', ' ', 'Hello World')
'Hello World'

Related

How to replace the multiple different words with a single character/word in Python? [duplicate]

This question already has answers here:
Better way to remove multiple words from a string?
(5 answers)
Closed 3 years ago.
Note: Without chaining replace method (or) looping the characters in for loop (or) list comprehension
input_string = "the was is characters needs to replaced by empty spaces"
input_string.replace("the","").replace("was","").replace("is","").strip()
output: 'characters needs to replaced by empty spaces'
Is there any direct way to do this?
You can use python regex module(re.sub) to replace multiple characters with a single character:
input_string = "the was is characters needs to replaced by empty spaces"
import re
re.sub("the|was|is","",input_string).strip()
'characters needs to replaced by empty spaces'
This should help..
input_string = "the was is characters needs to replaced by empty spaces"
words_to_replace=['the', 'was','is']
print(input_string)
for words in words_to_replace:
input_string = input_string.replace(words, "")
print(input_string.strip())

How to remove " " from text using regex-Python 3 [duplicate]

This question already has answers here:
Remove quotes from String in Python
(8 answers)
Closed 3 years ago.
So, I have a text string that I want to remove the "" from.
Here is my text string:
string= 'Sample this is a string text with "ut" '
Here is the output I want once using a regex expression:
string= 'Sample this is a string text with ut'
Here is my overall code:
import re
string= 'Sample this is a string text with "ut" '
re.sub('" "', '', string)
And the output just show the exact text in the string without any changes. Any suggestions?
You can simply use string.replace('"','')
If you want just remove all " symbols, you can use str.replace instead:
string = string.replace('"', '')

Python: Keeping whitespace at the beginning of a string [duplicate]

This question already has answers here:
Grab a line's whitespace/indention with Python
(6 answers)
Closed 5 years ago.
I Have a string that looks like this:
old_string = ' Some_text'
And I want to write a new string, but I would like to keep the same white-space at the beginning.
Is there a way in Python that I can keep this white-space?
The white-space could contain spaces or tabs, but the exact number of tabs or spaces is unknown.
I think this could be done using regex but I'm not sure if there is a way. And since the text in the string is not always the same I can't use
new_string = old_string.replace('Some_text','new_text')
any thoughts would be more than welcome.
You can do:
new_string = old_string[:-len(old_string.lstrip())] + 'new text'
Or if you prefer str.format:
new_string = '{}new text'.format(old_string[:-len(old_string.lstrip())])
Count how many characters get removed when you use lstrip;
str = ' Some_text'
whitespace = len(str) - len(str.lstrip())
print(whitespace)
Outputs;
6
You can use itertools.takewhile() to get the leading whitespace characters:
>>> from itertools import takewhile
>>> old_string = ' Some_text'
>>> whitespace = list(takewhile(str.isspace, old_string))
>>> "".join(whitespace)
' '
>>> len(whitespace)
6
To get the rest of the string you could use itertools.dropwhile():
>>> "".join(dropwhile(str.isspace, old_string))
'Some_text'

How can I split a pipe-separated string into a list? [duplicate]

This question already has answers here:
Split a string by a delimiter in python
(5 answers)
Closed 3 years ago.
I have this string:
var(HELLO,)|var(Hello again)| var(HOW ARE YOU?)|outV(0)|outV(1)|outV(2)|END
I want to split it on the |. I don't want it to split at the white space, only at the |.
Is this possible?
The way to do this is clearly documented here.
Example:
>>> myString = "subString1|substring2|subString3"
>>> myString = myString.split("|")
>>> print myString
["subString1", "subString2", "subString3"]

Python - How to ignore white spaces in double quotes while splitting a string? [duplicate]

This question already has answers here:
Split a string by spaces -- preserving quoted substrings -- in Python
(16 answers)
Closed 9 years ago.
I have my data as below
string = ' streptococcus 7120 "File being analysed" rd873 '
I tried to split the line using n=string.split() which gives the below result:
[streptococcus,7120,File,being,analysed,rd873]
I would like to split the string ignoring white spaces in " "
# output expected :
[streptococcus,7120,File being analysed,rd873]
Use re.findall with a suitable regex. I'm not sure what your error cases look like (what if there are an odd number of quotes?), but:
filter(None, it.chain(*re.findall(r'"([^"]*?)"|(\S+)', ' streptococcus 7120 "File being analysed" rd873 "hello!" hi')))
> ['streptococcus',
'7120',
'File being analysed',
'rd873',
'hello!',
'hi']
looks right.
You want shlex.split, which gives you the behavior you want with the quotes.
import shlex
string = ' streptococcus 7120 "File being analysed" rd873 '
items = shlex.split(string)
This won't strip extra spaces embedded in the strings, but you can do that with a list comprehension:
items = [" ".join(x.split()) for x in shlex.split(string)]
Look, ma, no regex!

Categories