Print out the elements in a string [closed] - python

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 5 years ago.
Improve this question
I have values that look like this
<type 'str'>
['zeven', 'nul', 'zeven', 'een', 'pieter', 'marie']
What I would like to do now is to loop over all the elements. However if I do like this:
x = ['zeven', 'nul', 'zeven', 'een', 'pieter', 'marie']
for word in x:
print(x)
I get:
[
'
z
e
Any thoughts how I can just get the values (like zeven, nul... etc...)

You are almost there, you should not print x but you should print word for each word in the list.
x = ['zeven', 'nul', 'zeven', 'een', 'pieter', 'marie']
for word in x:
print(word)
this will give you the following output:
zeven
nul
zeven
een
pieter
marie

It looks like you have something like this:
x = "['zeven', 'nul', 'zeven', 'een', 'pieter', 'marie']"
So you will need to use eval():
for word in eval(x):
print word

Related

How can I add a string to another in a specific place? [closed]

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 3 years ago.
Improve this question
I had some difficulty solving this challenge :
For each word in words, add ‘d’ to the end of the word if the word ends in “e” to make it past tense. Otherwise, add ‘ed’ to make it past tense. Save these past tense words to a list called past_tense.
words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
My attempt was :
enter code here:
words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
past_tense = []
for i in words:
if i[-1] == "e":
past_tense.append(i+"d")
else:
past_tense.append(i+"ed")
print(past_tense)
I am sure there is a more pythonic way on doing this, but this is quite understandable!
Using str.endswithas mentioned in the comments, will save you a lot of time!
words = ["adopt", "bake", "beam", "confide", "grill", "plant", "time", "wave", "wish"]
new_list=[]
for i in words:
if i.endswith('e'):
new_list.append(i+'d')
else:
new_list.append(i+'ed')
print(new_list)
This will output you past list!
['adopted', 'baked', 'beamed', 'confided', 'grilled', 'planted', 'timed', 'waved', 'wished']
I'd use an inline if-else construct in a list comprehension:
past_tense = [w + 'd' if w.endswith('e') else w + 'ed' for w in words]

How to choose a word that is in brackets from the sentence? [closed]

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 4 years ago.
Improve this question
How to choose
[Andrey] and [21] from info?
info = "my name is [Andrey] and I am [21] years old"
result = ["[Andrey]", "[21]"];
I am sure other ways would be better. But I tried this and it worked.
If you want to extract characters inside [] without knowing its position, you can use this method:
Run a for loop through string
If you find character [
append all the next characters in a string until you find ]
you can add these strings in a list to fetch result together. Here is the code.
info = "my name is [Andrey] and I am [21] years old"
s=[] #list to collect searched result
s1="" #elements of s
for i in range(len(info)):
if info[i]=="[":
while info[i+1] != "]":
s1 += info[i+1]
i=i+1
s.append(s1)
s1=""
#make s1 empty to search for another string inside []
print s
Output will be:
['Andrey', '21']
You may choose to regex method.
Or simply use list comprehension for your use case here:
>>> print([ lst[index] for index in [3,7] ])
['[Andrey]', '[21]']
But another way, You first convert your string to list and then choose by index method with the help of itemgetter:
>>> info = "my name is [Andrey] and I am [21] years old"
>>> lst = info.split()
>>> lst
['my', 'name', 'is', '[Andrey]', 'and', 'I', 'am', '[21]', 'years', 'old']
>>> from operator import itemgetter
>>> print(itemgetter(3,7)(lst))
('[Andrey]', '[21]')

Best way to iterate list with substrings and replace an upper string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I want to improve my code's performance and running time, looking for write my loops better.
For example, I have a dictionary that contains words as keys, and their translation in Spanish as values.
{
'Hello' : 'Hola',
'Goodbye' : 'Adios',
'Cheese' : 'Queso'
}
I also have a given English sentence, and I want to iterate over any word in my dict and replace it with the Spanish translation.
For this scenario I consider that up to one word could be exist in the given sentence.
I wrote a basic code that do that, but I am not sure that it is best practice:
words_list = {
'Hello' : 'Hola',
'Goodbye' : 'Adios',
'Cheese' : 'Queso'
}
sentence = "Hello, I want to talk Spanish"
for english_word in words_list.keys():
if english_word in sentence:
sentence = sentence.replace(english_word, words_list[english_word])
break
print sentence
How can I write it better?
Thanks!

get index of splited sentences from a string list [closed]

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 5 years ago.
Improve this question
The desired result is either a function or a way to find where is a sentence within a list of strings.
sentence = 'The cat went to the pool yesterday'
structure = ['The cat went,', 'to the pool yesterday.','I wonder if you realize the effect you are having on me. It hurts. A lot.']
for example
def findsentence(sentence, list of strings):
# do something to get the output, vec of positions to find the sentence in hte string list
return output
findsentence(sentence, structure)
> (0,1) # beacuse the phrase is splitted in the list...
Caution!!
The challenge it is not to find exactly the sentence. Look at the example, this sentence is part of sentence position 0 and part in structure postition 1.
So this is not a simple, string manipulation problem.
Use the following :
sentence = "foo sam bar go"
structure = ["rq", "foo sam", "bar go", "ca", "da"]
def findsentencelist(sentence, list_of_strings):
l = []
for item in list_of_strings:
if item in sentence:
l.append(list_of_strings.index(item))
return l
print str(findsentencelist(sentence, structure))
Hopefully this will help you, Yahli.
EDIT :
There is a problem with your variables.
Your sentence MUST be a string - not a list.
Edit your variables and try this function again :)
SECOND EDIT:
I think I've finally understood what you're trying to do. Let me know if this one works better.
THIRD EDIT:
Jesus, Hopefully this one would solve your problem. Let me know if it did the trick :)
I just remove punctuations on structure to make it work:
sentence = 'The cat went to the pool yesterday'
structure = ['The cat went,', 'to the pool yesterday.','I wonder if you realize the effect you are having on me. It hurts. A lot.','Life is too short as it is. In short, she had a cushion job.']
import string
def findsentence(sentence, list_of_strings):
return tuple(i for i, s in enumerate(list_of_strings) if s.translate(None, string.punctuation) in sentence)
print findsentence(sentence, structure)
# (0, 1)
After removing the punctuation. You can use this code to get the index ,
for i,j in enumerate(structure):
if j in sentence:
print(i)
Hope this solves your problems. There are quite other solutions as python is flexible.

Alphabetically order in python of a string [closed]

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 6 years ago.
Improve this question
I understand there is sort() function, but it won't work for me here. I would like to order alphabetically a string like follows:
'S NOM V NOUN VERB'
It should be:
'NOM NOUN S VERB V'
How can I achieve that in python?
Edit:
I have tried:
''.join(sorted(m[i][j]))
But this returned with very changed output like ABEILMNNNNOOPRSUVV for example which doesn't make sense.
You already have at least one good answer. You might as well abstract it into a function:
def sortWords(s, delim = ' '):
return delim.join(sorted(s.split(delim)))
For example,
>>> sortWords('S NOM V NOUN VERB')
'NOM NOUN S V VERB'
Try the following:
x = 'S NOM V NOUN VERB'
x = x.split() # produces ['S', 'NOM', 'V', 'NOUN', 'VERB']
x = sorted(x) # produces ['NOM', 'NOUN', 'S', 'V', 'VERB']
x = ' '.join(x) # produces 'NOM NOUN S V VERB'
You will have to use a custom sorting function if you want the order of V and VERB to be reversed (see the 'key' keyword for the sorted function).
You should split the string into a list then sort it and turn it back into a string. Here is an example.
old_string = "hello world abc"
string_list = old_string.split(" ") # split the string by a space, you can choose something different.
new_string = " ".join(string_list.sort()) # join list by a space.
print(new_string)

Categories