How can I remove whitespace in python? - python

Code,
Result
I want to remove the whitespace at the bracket point and the place before the percentage, how can I do that? Please can I know the simplest way to do it i dont want to over complicate the code

Build a string correctly formatted, then print it instead of using a continuation comma.
...
x = temp / 4
strx = str(x) + '%'
print "overall class grades... : " + strx
...

You can do this:
print('\nAfter the lowest mark({}) has been excluded'.format(a[0]))

Related

How can I ouput a string with qoutes with a 'for' loop printing the index and given string in Python?

I would like to print out a string containing double quotes after appending multiple items in a for loop. However, they currently disappear.
def print_five(word):
for i in range(1, 6):
print(f"{i}{word}", end=" ")
print_five("rock")
This is the output right now:
1rock 2rock 3rock 4rock 5rock
However..., this the desired output:
"1rock 2rock 3rock 4rock 5rock "
This should work. Use backslash to escape the characters.
def print_five(word):
five_word = f"1{word}"
for i in range(2, 6):
five_word = five_word + f" {i}{word}"
print(f"\"{five_word} \"")
A more elegant solution similar to the one that seems to have been deleted. Note that when working with strings that are supposed to contain double-quotes, it makes sense to work with f-strings using single quotes:
def print_five(word):
print(f'"{" ".join([f"{i}{word}" for i in list(range(1, 6))])} "')
print_five("rock")
# "1rock 2rock 3rock 4rock 5rock "

Having a string with two quotes around it?

How can I have a string like "'1'"? I have tried:
a = str(str(1))
but result still is '1'.
Use escape sequence:
print("\"\"1\"\"")
>> print("\"\"1\"\"")
""1""
BTW, this method is used by many people hence this is preferable :)
You can add those characters to your string using placeholders, doing so:
a = '"%s"'% a
You can use single quotes inside a double quoted string as mentioned above: "'1'" or '"1"' or you can escape quotes like '\'1\'' or "\"1\"". See for example Python Escape Characters.
Here is one way:
def single_quoted(s):
return "'" + s + "'"
def double_quoted(s):
return '"' + s + '"'
a = double_quoted(single_quoted(str(1)))
print(a)
It is very verbose so you can see what each individual part does, without inspecting your code carefully to find where each ' and " is. The output is
"'1'"
By the way, maybe you actually need this:
a = single_quoted(str(1))
print(a)
This outputs
'1'
If you want to use func call as you ask; try this solution:
str('\"1\"')

Replace only the ending of a string

It irks me not to be able to do the following in a single line. I've a feeling that it can be done through list comprehension, but how?
given_string = "first.second.third.None"
string_splitted = given_string.split('.')
string_splitted[-1] = "fourth"
given_string = ".".join(string_splitted)
Please note that the number of dots (.) in the given_string is constant (3). So i always want to replace the fourth fragment of the string.
It seems like you should be able to do this without splitting into an array. Find the last . and slice to there:
> given_string = "first.second.third.None"
> given_string[:given_string.rfind('.')] + '.fourth'
'first.second.third.fourth'
You could try this:
given_string = "first.second.third.None"
given_string = ".".join(given_string.split('.')[:-1] + ["fourth"])
print(given_string)
Output:
first.second.third.fourth
Try this one liner:-
print (".".join(given_string.split(".")[:-1]+["Fourth"]))
Output:
first.second.third.Fourth
You could use rsplit. This would work no matter how many dots precede the last split
given_string = "first.second.third.None"
string_splitted = given_string.rsplit('.', 1)[0] + '.fourth'
print(string_splitted)
first.second.third.fourth
my_string = "first.second.third.None"
my_sub = re.sub(r'((\w+\.){3})(\w+)', r'\1fourth', my_string)
print(my_sub)
first.second.third.fourth
A good explanation of this style is here: How to find and replace nth occurence of word in a sentence using python regular expression?

regular expression replace (if pattern found replace symbol for symbol)

I have several lines of text (RNA sequence), I want to make a matrix regarding conservation of characters, because they are aligned according similarity.
But I have several gaps (-) which actually mean missing a whole structure (e.g.#- > 100) If this happens I want to change that for dots (other symbol for making a distinguishment) with the same amount found.
I thought I can do this with regular expression, but I am not able to replace only the pattern, or when I do so, I replace everything but with the incorrect number of dots.
My code looks like this:
with alnfile as f_in:
if re.search('-{100,}', elem,):
elem = re.sub('-{100,}','.', elem, ) #failed alternative*len(m.groups(x)), elem)
print len(elem) # check if I am keeping the lenghth of my sequence
print elem[0:100] # check the start
f1.write(elem)
if my file is:
ONE ----(*100)atgtgca----(*20)
I am getting:
ONE ..(*100)atgtgca----(*20)
My other change was only dots then I get:
ONE ....(*100)atgtgca....(*20)
WHAT I NEED:
ONE ....(*100)atgtgca----(*20)
I know that I am missing something, but I can not figure it out? Is there a flag or something that help me or would allow the exact change of this?
You could try the following:
data = "ONE " + "-" * 100 + "atgtgca" + "-" * 20
print re.sub(r'-{100,}', lambda x: '.' * len(x.group(0)), data)
This would display:
ONE ....................................................................................................atgtgca--------------------

Python 2.7 string

I need to print [something] only one time, even if exactly the same string occurs next time. I tried this:
msg = "[something]" + random.randint(1,5)*str(random.randint(1,1000000000)) + "[something]"
i = msg[msg.index('['):msg.rindex(']')+1]
print i
but it works wrong. Message is prints up to last "]", I would like it to be up to the first "]". Between two "[something]" is randomly amount of strings. Is it posible with this code?
Here are two ways you could do it:
import re
msg = "[something]" + random.randint(1,5)*str(random.randint(1,1000000000)) + "[something]"
print msg[msg.index('['):msg.index(']')+1]
print re.search("(\[.*?\])", msg).group(1)
Which will display:
[something]
[something]
Use msg.index(']') instead of msg.rindex(']') as the last method searches "]" from the end of the string. For more details, see the doc.

Categories