Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a problem like:
name = "Steve Jobs is my name."
Desired output:
['Steve Jobs', 'is', 'my name.']
My tried solution:
I have tried using the split function in Python.
Code:
result = name.split()
['Steve', 'Jobs', 'is', 'my', 'name']
I am unable to proceed from here. I have tried using for loop.
But, I am not getting the required result.
Am I missing something or is there any other way of solving this problem?
Please let me know.
This seems like the kind of interview question where they just want to find out how you think. In this case, with just one example to go on, I would look for a pattern that gets you to the desired output.
For example, you could split on " is " to get the two parts before and after, then insert "is" back in the middle of the list to get the desired result.
name = "Steve Jobs is my name."
result = name.split(" is ")
result .insert(1, "is")
print(result )
Assuming this is a trick question:
[x.strip() for x in name.partition("is")]
If you split the string using string.split(), the string will be split at ever occurrence of " " (space). But in your case, you want to split it at a specific place instead of at every occurrence of space.
you can try using:
result1 = [name[:10], name[11:13], name[14:]]
but this is only applicable if you wanna split this specific string.
If you want to split different strings that are of similar sentence structure, you can try:
words = name.split()
result = [words[0] + " " + words[1], words[2], words[3] + " " + words[4]]
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Let’s say I have this:
text = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”
letter = “N”
new_text = function(text, letter)
print(new_text)
Is is possible to create a function that the output is
NOPQRSTUVWXYZABCDEFGHIJKLM
With str.partition:
>>> left, letter, right = text.partition(letter)
>>> out = letter + right + left
>>> out
"NOPQRSTUVWXYZABCDEFGHIJKLM"
text = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
text[text.find('N'):] + text[: text.find('N')]
'NOPQRSTUVWXYZABCDEFGHIJKLM'
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i have a txt file with several words on it, does anybody know how to duplicate each word two times as the next example
hello
bye
hello
hello
hello
bye
bye
bye
regards
You could do something like this, but for sure there are better solutions:
text ="hello bye"
text_out = []
times_to_duplicate = 3
for word in text.split(" "):
for i in range(times_to_duplicate + 1):
text_out.append(word)
" ".join(text_out)
Or as list comprehention, as #Sushanth states:
"".join(f"{x} " * 3 for x in "hello bye".split())
I would recommend you, before asking a question to check the grammar and punctuation to improve the quality of your question
In python, you can replicate a string by multiplying the string n number of times.
example: this will repeat hello 3 times
>>> 'hello' * 3
'hellohellohello'
If you want a space between that, then you can do it as follows:
>>> 'hello ' * 3
'hello hello hello '
Using this as your base, you can write the code as follows to get the desired result.
txt = 'hello bye'
#now split the word and iterate thru each word by creating a new list
txt1 = [(t+' ')*3 for t in txt.split(' ')]
#you now have a new list txt1 with repeated words
#if you want it as a single string, you need to concatenate that using join
txt2 = ' '.join(txt1)
print (txt2)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to take a user inputed string and, if it ends with 'ion', replace the last three characters of the string and add an 'e'.
def ion2e(s):
if s[-3:]=='ion':
print (s[-3:]+'e')
else:
print (s)
Use str.endswith:
>>> def ion2e(s):
... return s[:-3] + 'e' if s.endswith('ion') else s
...
>>> ion2e('xxxion')
'xxxe'
>>> ion2e('xx')
'xx'
s[-3:] says
give me s starting 3 digits backwards from the end, and going to the end
But what you want is s up to 3 digits backwards from the end. Which would be:
s[:-3]
So your whole code should be:
def ion2e(s):
if s[-3:]=='ion':
print (s[:-3]+'e')
else:
print (s)
Move the colon in your print. You need the string up to the -3rd element, not the end of the string.
def ion2e(s):
if s[-3:]=='ion':
print (s[:-3]+'e')
else:
print (s)
t = "constitution"
ion2e(t)
Also, are you familiar with single-statement if expressions? Your function might be reduced to this, if you want to return the value instead of printing it.
def ion2e(s):
return s[:-3]+'e' if s[-3:]=='ion' else s
You may also want to use re
import re
print (re.sub("ion$", "e", 'station'))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I've a string like this Delete File/Folder. I need to break the sentence based on the / equivalent to or.
Finally need to generate two strings out of this like Delete File as one string and Delete Folder as the other one.
I've tried very naive way where I check for the index of / and then form strings with a bunch of conditions.
It some times fails when we have string like File/Folder Deleted.
Edit:
If you split on / then for case 1 we have Delete File and Folder. Then I'll check for spaces present in first string and spaces present is second string.
The one which has less number of spaces will be replaced with first string last element. This is getting complicated.
In the case of Delete File/Folder, thinking through why the word Delete gets distributed to both of File and Folder might help with the inherent assumptions we all intuitively make when lexical parsing.
For instance, it would be parsed between the the i and l to return ["Delete File", "Delete FiFolder"].
It sounds like you want to want to split the string into words based on where there are spaces and then split each word based on / to generate new full strings.
>>> import itertools
>>> my_str = "Delete File/Folder"
>>> my_str = ' '.join(my_str.split()).replace('/ ', '/').replace(' /', '/') # First clean string to ensure there aren't spaces around `/`
>>> word_groups = [word.split('/') for word in my_str.split(' ')]
>>> print [' '.join(words) for words in itertools.product(*word_groups)]
['Delete File', 'Delete Folder']
Do you want that? Comment if you want a more generalized solution.
lst = your_string.split()[1].split("/")
finalList=[]
for i in lst:
finalList.append("Delete {0}",i)
print finalList
For string:
Delete File/Folder
Output:
['Delete File', 'Delete Folder']
str = "Do you want to Delete File/Folder?"
word = str.split(" ")
count = str.count("/")
c = True
for j in range(0,2*count):
for i in word:
if("/" in i):
words = i.split("/")
if c:
print words[1],
else:
print words[0],
else:
print i, # comma not to separate line
c = not c
print
output
Do you want to Delete File
Do you want to Delete Folder?
st1 = "Do you want to Delete File/Folder"
st2 = "File/Folder Updated"
def spl(st):
import re
li = []
ff = re.search(r'\w+/\w+',st).group()
if ff:
t = ff.split('/')
l = re.split(ff,st)
for el in t:
if not l[0]:
li.append((el + ''.join(l)))
else:
li.append((''.join(l) + el))
return li
for item in st1,st2:
print(spl(item))
['Do you want to Delete File', 'Do you want to Delete Folder']
['File Updated', 'Folder Updated']
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In python, how do you reverse the order of words in a string and also reverse the order of the letters in the word.
For example, if the input is:
Hello world
The output should be:
olleH dlrow
My attempt:
a=input('Line: ')
print(a[::-1])
Your desired output conflicts with the description of your requirements viz "how do you reverse the order of words in a string and also reverse the order of the letters in the word.". That would simply be the same as reversing the string, which you have already provided as your solution. Instead, to reverse the the letters in each word, but retain the order of those words, you can use split() and a reverse slice ([::-1]) on each word.
s = "Hello world"
for word in s.split():
print word[::-1],
Or, like this:
print ' '.join(word[::-1] for word in s.split())
The above assumes that you do not need to retain the exact whitespace between words.
You may try this using the slice option:
def reverseOrder(strs):
return ''.join([strs[i] for i in xrange(len(strs)-1, -1, -1)])
or better try this:
>>> s='Hello World'
>>> ' '.join(w[::-1] for w in s.split())
'olleH dlrow'