I have the input s of string. I want to print string s in which all the occurrences of WUB are replaced with a white space.
s = input()
print(s.split("WUB"))
Input : WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB
but the output I am getting is like this
: ['', 'WE', 'ARE', '', 'THE', 'CHAMPIONS', 'MY', 'FRIEND', '']
instead I need output in string format, like this : WE ARE THE CHAMPIONS MY FRIEND
You can join the strings in the list produced by split with a space:
print(" ".join(s.split("WUB")))
You can also just use replace instead of split + join:
print(s.replace("WUB", " "))
You can apply the input in the print statement like this
s = input()
print(*s.split("WUB"))
Notice * before s.split("WUB") this gives the desired output.
WE ARE THE CHAMPIONS MY FRIEND
Just join all elements from your list. See it below:
print(" ".join("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB".split("WUB")).strip())
Related
I need to write a program that replaces all inputted values in a string. Thus: the string reads as "[link1], [link2], [link3]", the input is "1, 2", I want to replace both [link1] and [link2] with another text.
I've tried both replace() and re.sub, but these expectedly only change the first occurrence of the pattern. What am I doing wrong?
for i in input:
output = string.replace(f'[link{i}]', '')
# output = re.sub(f'[link{i}]', '', string)
return output
In your code, you are not saving the modified string. It is just changing the raw string every time and saving only one change.
Try like this:
string = "[link1], [link2], [link3]"
INPUT = input('Give the input').split(',')
replacer = {'1' : 'ONE', "2" : 'Two', '3' : 'Three'}
for i in INPUT:
string = string.replace(f'[link{i}]', replacer[i])
print(string)
I'm a novice in python programming and i'm trying to split full name to first name and last name, can someone assist me on this ? so my example file is:
Sarah Simpson
I expect the output like this : Sarah,Simpson
You can use the split() function like so:
fullname=" Sarah Simpson"
fullname.split()
which will give you: ['Sarah', 'Simpson']
Building on that, you can do:
first=fullname.split()[0]
last=fullname.split()[-1]
print(first + ',' + last)
which would give you Sarah,Simpson with no spaces
This comes handly : nameparser 1.0.6 - https://pypi.org/project/nameparser/
>>> from nameparser import HumanName
>>> name = "Sarah Simpson"
>>> name = HumanName(name)
>>> name.last
'Simpson'
>>> name.first
'Sarah'
>>> name.last+', '+name.first
'Simpson, Sarah'
you can try the .split() function which returns a list of strings after splitting by a separator. In this case the separator is a space char.
first remove leading and trailing spaces using .strip() then split by the separator.
first_name, last_name=fullname.strip().split()
Strings in Python are immutable. Create a new String to get the desired output.
You can use split() method of string class.
name = "Sarah Simpson"
name.split()
split() by default splits on whitespace, and takes separator as parameter. It returns a list
["Sarah", "Simpson"]
Just concatenate the strings. For more reference https://docs.python.org/3.7/library/stdtypes.html?highlight=split#str.split
Output = "Sarah", "Simpson"
name = "Thomas Winter"
LastName = name.split()[1]
(note the parantheses on the function call split.)
split() creates a list where each element is from your original string, delimited by whitespace. You can now grab the second element using name.split()[1] or the last element using name.split()[-1]
split() is obviously the function to go for-
which can take a parameter or 0 parameter
fullname="Sarah Simpson"
ls=fullname.split()
ls=fullname.split(" ") #this will split by specified space
Extra Optional
And if you want the split name to be shown as a string delimited by coma, then you can use join() or replace
print(",".join(ls)) #outputs Sarah,Simpson
print(st.replace(" ",","))
Input: Sarah Simpson => suppose it is a string.
Then, to output: Sarah, Simpson. Do the following:
name_surname = "Sarah Simpson".split(" ")
to_output = name_surname[0] + ", " + name_surname[-1]
print(to_output)
The function split is executed on a string to split it by a specified argument passed to it. Then it outputs a list of all chars or words that were split.
In your case: the string is "Sarah Simpson", so, when you execute split with the argument " " -empty space- the output will be: ["Sarah", "Simpson"].
Now, to combine the names or to access any of them, you can right the name of the list with a square brackets containing the index of the desired word to return. For example: name_surname[0] will output "Sarah" since its index is 0 in the list.
I have a text file something like this (suppose A and B are persons and below text is a conversation between them):
A: Hello
B: Hello
A: How are you?
B: I am good. Thanks and you?
I added this conversation into a list that returns below result:
[['A', 'Hello\n'], ['A', 'How are you?\n'], ['B', 'Hello\n'], ['B', 'I am good. Thanks and you?\n']]
I use these commands in a loop:
new_sentence = line.split(': ', 1)[1]
attendees_and_sentences[index].append(person)
attendees_and_sentences[index].append(new_sentence)
print(attendees_and_sentences) # with this command I get the above result
print(attendees_and_sentences[0][1]) # if I run this one, then I don't get "\n" in the sentence.
The problem is those "\n" characters on my result screen. How can I get rid of them?
Thank you.
You can use Python's rstrip function.
For example:
>>> 'my string\n'.rstrip()
'my string'
And if you want to trim the trailing newlines while preserving other whitespace, you can specify the characters to remove, like so:
>>> 'my string \n'.rstrip()
'my string '
I`m working with documents, and I need to have the words isolated without punctuation. I know how to use string.split(" ") to make each word just the letters, but the punctuation baffles me.
this is an example using regex, and the result is
['this', 'is', 'a', 'string', 'with', 'punctuation']
s = " ,this ?is a string! with punctuation. "
import re
pattern = re.compile('\w+')
result = pattern.findall(s)
print(result)
Is it possible to use a regex so as to obtain the following features ?
text = "123abcd56EFG"
listWanted = ["123", "abcd", "56", "EFG"]
The idea is to cut the texte each time one digit is followed by one letter, or one letter is followed by one digit.
The solution thanks to the following answer
import re
pattern = r'(\d+|\D+)'
text = "123abcd56EFG"
print(re.split(pattern, text))
text = "abcd56EFG"
print(re.split(pattern, text))
This code will give...
['', '123', '', 'abcd', '', '56', '', 'EFG', '']
['', 'abcd', '', '56', '', 'EFG', '']
Use a capturing group in your regex.
>>> import re
>>> text = "123abcd56EFG"
>>> pattern = r'(\d+)'
>>> re.split(pattern, text)
['', '123', 'abcd', '56', 'EFG']
While this will give you empty strings at the start and/or end for lines with digit groups at the start and/or end, those are easy enough to trim off.
You're going to want to do a split using: \d+|\D+ as your Regex.
--note that you need excape sequences to make the \ in your string, so the actual text entered will be: "\\d+|\\D+"
UNLESS, as noted in the comment below, you use a raw string, in which case it would be r"\d+|\D+" or r'\d+|\D+'