How do I remove parentheses and single quotation marks from my output? There is no requirement in my code to show brackets and single quotation marks.
person = " xx "
what_he_said = " abc!"
print(f"{person.split()}曾经说过,“{what_he_said.split()}”")
This is the actual output:
['xx']曾经说过,“['abc!']”
I don't want to output the middle brackets and quotation marks.
I'm using Python 3.10, the IDE is pycharm.
The result of split is a list. If you want the str without surrounding space, you should use strip
person = " xx "
what_he_said = " abc!"
print(f"{person.strip()}曾经说过,“{what_he_said.strip()}”")
Just to print you can try:
Supposing it's necessary to use .split()
person = " xx "
what_he_said = " abc!"
print(*person.split(),'曾经说过',*what_he_said.split())
The split() function will separate the data with the [sep] parameter, it's empty by default, I assume you're using split to remove "[space-k]", but note that it will always return a separate argument list
"hola como estas ".split(sep=" ")
will return:
[hola, como, estas]
If you really need to use the split() function, you can get its values with the index.
E.g
person = " xx "
what_he_said = " abc!"
print(f"{person.split()[0]}曾经说过,“{what_he_said.split()[0]}”")
will return:
xx曾经说过,“abc!”
Related
I have a string similar to (the below one is simplified):
" word= {his or her} whatever "
I want to delete every whitespace except between {}, so that my modified string will be:
"word={his or her}whatever"
lstrip or rstrip doesn't work of course. If I delete all whitespaces the whitespaces between {} are deleted as well. I tried to look up solutions for limiting the replace function to certain areas but even if I found out it I haven't been able to implement it. There are some stuff with regex (I am not sure if they are relevant here) but I haven't been able to understand them.
EDIT: If I wanted to except the area between, say {} and "", that is:
if I wanted to turn this string:
" word= {his or her} and "his or her" whatever "
into this:
"word={his or her}and"his or her"whatever"
What would I change
re.sub(r'\s+(?![^{]*})', '', list_name) into?
See instead going arround re you can replace uisng string.replace. Which will be much more easier and less complex when you playing around strings. Espacillay when you have multiple substitutions you end up bigger regex.
st =" word= {his or her} whatever "
st2=""" word= {his or her} and "his or her" whatever """
new = " ".join(st2.split())
new = new.replace("= ", "=").replace("} ", "}").replace('" ' , '"').replace(' "' , '"')
print(new)
Some outputs
Example 1 output
word={his or her}whatever
Example 2 output
word={his or her}and"his or her"whatever
You can use by replace
def remove(string):
return string.replace(" ", "")
string = 'hell o whatever'
print(remove(string)) // Output: hellowhatever
repalce a string with python
I have tried the replace function but it gives me an str error
a="test1,test2"
a="\""+a.replace(",","\",\"")+"\""
print(a)
So this is the answer to what you asked.
old_string = "test1,test2"
new_string = old_string.replace(',', '","')
# new_string = 'test1","test2'
When you want to use " in a string, you can use the single quote for the string.
However are you sure you are not looking for the split functionality.
I am not sure why the first asterisk is not printing, does anyone have any ideas? BTW I am using a dictionary.
input
error
output
' ****'
expected output
'*****'
MORSE_CODES={'A':'.-','B':'-...','C':'-.-.',
'D':'-..','E':'.','F':'..-.','G':'--.',
'H':'....','I':'..','J':'.---','K':'-.-',
'L':'.-..','M':'--','N':'-.','O':'---',
'P':'.--.','Q':'--.-','R':'.-.',
'S':'...','T':'-','U':'..-','V':'...-',
'W':'.--','X':'-..-','Y':'-.--','Z':'--..'}
def encode_Morse(my_msg):
my_msg_Morse=" "
for letter in my_msg:
if letter!=" " and letter not in MORSE_CODES:
my_msg_Morse+="*"
elif letter!=" ":
my_msg_Morse+= MORSE_CODES[letter]+" "
else:
my_msg_Morse+=" "
my_msg_Morse = my_msg_Morse[:-1]
return my_msg_Morse
The problem is that you are not returning the full string and that the last asterisk is not printing. You can fix this problem by amending the assignment my_msg_Morse = my_msg_Morse[:-1]
to
my_msg_Morse = my_msg_Morse.
If you weren't adding blank spaces with this condition (for the characters matched by your dictionary - i.e. the capital letters)
elif letter!=" ":
my_msg_Morse+= MORSE_CODES[letter]+" "
it would be more clear that you have this problem generally. Consider the test case where you don't add blanks:
Input:
ERROR
Expected Output:
..-..-.---.-.
Actual Output:
..-..-.---.-
However, you are adding blank spaces after each rendering of a capital into morse code. So this loss of the final character (a blank space) is mostly unobserved.
I don't know what your requirements are but if they are satisfied by returning a string with no trailing white space you could return my_msg_Morse.rstrip(). The rstrip() method of the string object removes all trailing white space. This way, you could preserve your within-string white space while eliminating trailing white space. I also like Tim Robert's suggestion (in a comment to your original question) of using a list and joining it.
I'm quite new to programming (and this is my first post to stackoverflow) however am finding this problem quite difficult. I am supposed to remove a given string in this case (WUB) and replace it with a space. For example: song_decoder(WUBWUBAWUBWUBWUBBWUBC) would give the output: A B C. From other questions on this forums I was able to establish that I need to replace "WUB" and to remove whitespace use a split/join. Here is my code:
def song_decoder(song):
song.replace("WUB", " ")
return " ".join(song.split())
I am not sure where I am going wrong with this as I the error of WUB should be replaced by 1 space: 'AWUBBWUBC' should equal 'A B C' after running the code. Any help or pointing me in the right direction would be appreciated.
You're close! str.replace() does not work "in-place"; it returns a new string that has had the requested replacement performed on it.
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
Do this instead:
def song_decoder(song):
song = song.replace("WUB", " ")
return " ".join(song.split())
For example:
In [14]: song_decoder("BWUBWUBFF")
Out[14]: 'B FF'
Strings are immutable in Python. So changing a string (like you try to do with the "replace" function) does not change your variable "song". It rather creates a new string which you immediately throw away by not assigning it to something. You could do
def song_decoder(song):
result = song.replace("WUB", " ") # replace "WUB" with " "
result = result.split() # split string at whitespaces producing a list
result = " ".join(result) # create string by concatenating list elements around " "s
return result
or, to make it shorter (one could also call it less readable) you can
def song_decoder(song):
return " ".join(song.replace("WUB", " ").split())
Do the both steps in a single line.
def song_decoder(song):
return ' '.join(song.replace('WUB',' ').split())
Result
In [95]: song_decoder("WUBWUBAWUBWUBWUBBWUBC")
Out[95]: 'A B C'
I have a CSV file, where each comma delimited field is enclosed in " - eg. "fred", "bert", "blah". I am trying to use the replace function but can't seem to have it recognize the " character. example, if the record is in a string called buffer:
buffer.replace('\"','')
Add space between double quotes
p = '"fred", "bert", "blah"'
p.replace('\"'," ")
' fred , bert , blah '
Why do you escape the double quotes if it's inside single quotes ?
Try the following :
a = '"my string"'
a = a.replace('"',' ')
print(a)
#=> ' my string '
You are not replacing it with space firstly, but with empty string
Try using buffer.strip("\"")