I am trying to code a program which will ask for a person's full name (first, middle, last) and will print (last, middle, tsrif). Like print their name backwards, but the letters are backwards only on their first name. I can't figure out how to flip the order of the words without flipping their letters. Any help?
My code so far:
import sys
str = raw_input("first middle last")
str.split( );
>>> my_string = raw_input('?: ').split()
?: first middle last
>>> new_string = ' '.join(my_string[:0:-1] + [my_string[0][::-1]])
>>> new_string
'last middle tsrif'
>>> s = 'first middle last'
>>> L = s.split()
>>> L[0] = L[0][::-1]
>>> L
['tsrif', 'middle', 'last']
>>> print L[::-1]
['last', 'middle', 'tsrif']
Reverse the list at first. Then reverse the last string in list
my_list = string.split()
my_list = list(reversed(my_list))
my_list[2] = my_list[2][::-1]
print my_list
Don't use str as variable.
This should work
import sys
str = "first middle last";
allWords = str.split(" ");
length = len(allWords)
for index in range(length-1):
print(allWords[length-index-1],end=" ")
print((allWords[0])[::-1])
The str.split() function returns the list, it doesn't modify it in place. So you want :
split_up = str.split()
(obviously split_up is an arbitrary name, the point is that it's a list)
input_name = "first middle last" # whatever your input is: using as example here
split_name = input_name.split()
desired_output = [split_name [2], split_name [1], split_name [0][::-1]]
>>> desired_output
['last', 'middle', 'tsrif']
>>> ' '.join(desired_output)
'last middle tsrif'
>>> ', '.join(desired_output)
'last, middle, tsrif'
Let's assume you have a variable s which you've gotten from the user. If you want to split that up into individual words, you use .split() and save the result
s = "john henry smith"
parts = s.split() # ['john', 'henry', 'smith']
now, to reverse these words, you can use the built in function reversed and convert the result to a list
rev_parts = list(reversed(parts)) # ['smith', 'henry', 'john']
Finally you want to reverse just the last element of rev_parts, you can use a -1 index to indicate the last element in the list. What you want to do is overwrite the existing element. We can use reversed again here, but we'll also need to use a join to tell it to but all the characters back together after
rev_name = ''.join(reversed(rev_parts[-1])) # 'nhoj'
rev_parts[-1] = rev_name # overwrite 'john'
Now you have a list of what you want. If you want to put them all back together separated by spaces, use another join
result = ' '.join(rev_parts)
You can eliminate various intermediate variables and steps here as you feel comfortable.
An alternative to using reversed is to use the slice syntax [::-1] which says, from the end to the beginning, back one character at a time. In that case you'd have
rev_parts = parts[::-1]
rev_parts[-1] = rev_parts[-1][::-1]
Related
So I have a long list of column headers. All are strings, some are several words long. I've yet to find a way to write a function that extracts the first word from each value in the list and returns a list of just those singular words.
For example, this is what my list looks like:
['Customer ID', 'Email','Topwater -https:', 'Plastics - some uml']
And I want it to look like:
['Customer', 'Email', 'Topwater', 'Plastics']
I currently have this:
def first_word(cur_list):
my_list = []
for word in cur_list:
my_list.append(word.split(' ')[:1])
and it returns None when I run it on a list.
You can use list comprehension to return a list of the first index after splitting the strings by spaces.
my_list = [x.split()[0] for x in your_list]
To address "and it returns None when I run it on a list."
You didn't return my_list. Because it created a new list, didn't change the original list cur_list, the my_list is not returned.
To extract the first word from every value in a list
From #dfundako, you can simplify it to
my_list = [x.split()[0] for x in cur_list]
The final code would be
def first_word(cur_list):
my_list = [x.split()[0] for x in cur_list]
return my_list
Here is a demo. Please note that some punctuation may be left behind especially if it is right after the last letter of the name:
names = ["OMG FOO BAR", "A B C", "Python Strings", "Plastics: some uml"]
first_word(names) would be ['OMG', 'A', 'Python', 'Plastics:']
>>> l = ['Customer ID', 'Email','Topwater -https://karls.azureedge.net/media/catalog/product/cache/1/image/627x470/9df78eab33525d08d6e5fb8d27136e95/f/g/fgh55t502_web.jpg', 'Plastics - https://www.bass.co.za/1473-thickbox_default/berkley-powerbait-10-power-worm-black-blue-fleck.jpg']
>>> list(next(zip(*map(str.split, l))))
['Customer', 'Email', 'Topwater', 'Plastics']
[column.split(' ')[0] for column in my_list] should do the trick.
and if you want it in a function:
def first_word(my_list):
return [column.split(' ')[0] for column in my_list]
(?<=\d\d\d)\d* try using this in a loop to extract the words using regex
so i'm trying to make a program in Python PyScripter 3.3 that takes input, and converts the input into an acronym. This is what i'm looking for.
your input: center of earth
programs output: C.O.E.
I don't really know how to go about doing this, I am looking for not just the right answer, but an explanation of why certain code is used, thanks..
What I have tried so far:
def first_letters(lst):
return [s[:1] for s in converted]
def main():
lst = input("What is the phrase you wish to convert into an acronym?")
converted = lst.split().upper()
Beyond here I am not really sure where to go, so far I know I need to captialize the input, split it into separate words, and then beyond that im not sure where to go...
I like Python 3.
>>> s = 'center of earth'
>>> print(*(word[0] for word in s.upper().split()), sep='.', end='.\n')
C.O.E.
s = 'center of earth' - Assign the string.
s.upper() - Make the string uppercase. This goes before split() because split() returns a list and upper() doesn't work on lists.
.split() - Split the uppercased string into a list.
for word in - Iterate through each element of the created list.
word[0] - The first letter of each word.
* - Unpack this generator and pass each element as an argument to the print function.
sep='.' - Specify a period to separate each printed argument.
end='.\n' - Specify a period and a newline to print after all the arguments.
print - Print it.
As an alternative:
>>> s = 'center of earth'
>>> '.'.join(filter(lambda x: x.isupper(), s.title())) + '.'
'C.O.E.'
s = 'center of earth' - Assign the string.
s.title() - Change the string to Title Case.
filter - Filter the string, retaining only those elements that are approved by a predicate (the lambda below).
lambda x: x.isupper() - Define an anonymous inline function that takes an argument x and returns whether x is uppercase.
'.'.join - Join all the filtered elements with a '.'.
+ '.' - Add a period to the end.
Note that this one returns a string instead of simply printing it to the console.
>>> import re
>>> s = "center of earth"
>>> re.sub('[a-z ]+', '.', s.title())
'C.O.E.'
>>> "".join(i[0].upper() + "." for i in s.split())
'C.O.E.'
Since you want an explanation and not just an answer:
>>> s = 'center of earth'
>>> s = s.split() # split it into words
>>> s
['center', 'of', 'earth']
>>> s = [i[0] for i in s] # get only the first letter or each word
>>> s
['c', 'o', 'e']
>>> s = [i.upper() for i in s] # convert the letters to uppercase
>>> s
['C', 'O', 'E']
>>> s = '.'.join(s) # join the letters into a string
>>> s
'C.O.E'
>>> s = s + '.' # add the dot at the end
>>> s
'C.O.E.'
How do I concatenate a list of strings into a single string?
For example, given ['this', 'is', 'a', 'sentence'], how do I get "this-is-a-sentence"?
For handling a few strings in separate variables, see How do I append one string to another in Python?.
For the opposite process - creating a list from a string - see How do I split a string into a list of characters? or How do I split a string into a list of words? as appropriate.
Use str.join:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
A more generic way (covering also lists of numbers) to convert a list to a string would be:
>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
12345678910
It's very useful for beginners to know
why join is a string method.
It's very strange at the beginning, but very useful after this.
The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).
.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).
Once you learn it, it's very comfortable and you can do tricks like this to add parentheses.
>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'
>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'
Edit from the future: Please don't use the answer below. This function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.
Although #Burhan Khalid's answer is good, I think it's more understandable like this:
from str import join
sentence = ['this','is','a','sentence']
join(sentence, "-")
The second argument to join() is optional and defaults to " ".
list_abc = ['aaa', 'bbb', 'ccc']
string = ''.join(list_abc)
print(string)
>>> aaabbbccc
string = ','.join(list_abc)
print(string)
>>> aaa,bbb,ccc
string = '-'.join(list_abc)
print(string)
>>> aaa-bbb-ccc
string = '\n'.join(list_abc)
print(string)
>>> aaa
>>> bbb
>>> ccc
We can also use Python's reduce function:
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
We can specify how we join the string. Instead of '-', we can use ' ':
sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)
If you have a mixed content list and want to stringify it, here is one way:
Consider this list:
>>> aa
[None, 10, 'hello']
Convert it to string:
>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'
If required, convert back to the list:
>>> ast.literal_eval(st)
[None, 10, 'hello']
If you want to generate a string of strings separated by commas in final result, you can use something like this:
sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"
def eggs(someParameter):
del spam[3]
someParameter.insert(3, ' and cats.')
spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
Without .join() method you can use this method:
my_list=["this","is","a","sentence"]
concenated_string=""
for string in range(len(my_list)):
if string == len(my_list)-1:
concenated_string+=my_list[string]
else:
concenated_string+=f'{my_list[string]}-'
print([concenated_string])
>>> ['this-is-a-sentence']
So, range based for loop in this example , when the python reach the last word of your list, it should'nt add "-" to your concenated_string. If its not last word of your string always append "-" string to your concenated_string variable.
s = ['my', 'name']
I want to change the 1st letter of each element in to Upper Case.
s = ['My', 'Name']
Both .capitalize() and .title(), changes the other letters in the string to lower case.
Here is a simple function that only changes the first letter to upper case, and leaves the rest unchanged.
def upcase_first_letter(s):
return s[0].upper() + s[1:]
You can use the capitalize() method:
s = ['my', 'name']
s = [item.capitalize() for item in s]
print s # print(s) in Python 3
This will print:
['My', 'Name']
You can use 'my'.title() which will return 'My'.
To get over the complete list, simply map over it like this:
>>> map(lambda x: x.title(), s)
['My', 'Name']
Actually, .title() makes all words start with uppercase. If you want to strictly limit it the first letter, use capitalize() instead. (This makes a difference for example in 'this word' being changed to either This Word or This word)
It probably doesn't matter, but you might want to use this instead of the capitalize() or title() string methods because, in addition to uppercasing the first letter, they also lowercase the rest of the string (and this doesn't):
s = map(lambda e: e[:1].upper() + e[1:] if e else '', s)
Note: In Python 3, you'd need to use:
s = list(map(lambda e: e[:1].upper() + e[1:] if e else '', s))
because map() returns an iterator that applies function to every item of iterable instead of a list as it did in Python 2 (so you have to turn it into one yourself).
You can use
for i in range(len(s)):
s[i]=s[i].capitalize()
print s
Is there a quick way in Python to replace strings but, instead of starting from the beginning as replace does, starting from the end? For example:
>>> def rreplace(old, new, occurrence)
>>> ... # Code to replace the last occurrences of old by new
>>> '<div><div>Hello</div></div>'.rreplace('</div>','</bad>',1)
>>> '<div><div>Hello</div></bad>'
>>> def rreplace(s, old, new, occurrence):
... li = s.rsplit(old, occurrence)
... return new.join(li)
...
>>> s
'1232425'
>>> rreplace(s, '2', ' ', 2)
'123 4 5'
>>> rreplace(s, '2', ' ', 3)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 4)
'1 3 4 5'
>>> rreplace(s, '2', ' ', 0)
'1232425'
Here is a one-liner:
result = new.join(s.rsplit(old, maxreplace))
Return a copy of string s with all occurrences of substring old replaced by new. The first maxreplace occurrences are replaced.
and a full example of this in use:
s = 'mississipi'
old = 'iss'
new = 'XXX'
maxreplace = 1
result = new.join(s.rsplit(old, maxreplace))
>>> result
'missXXXipi'
I'm not going to pretend that this is the most efficient way of doing it, but it's a simple way. It reverses all the strings in question, performs an ordinary replacement using str.replace on the reversed strings, then reverses the result back the right way round:
>>> def rreplace(s, old, new, count):
... return (s[::-1].replace(old[::-1], new[::-1], count))[::-1]
...
>>> rreplace('<div><div>Hello</div></div>', '</div>', '</bad>', 1)
'<div><div>Hello</div></bad>'
Just reverse the string, replace first occurrence and reverse it again:
mystr = "Remove last occurrence of a BAD word. This is a last BAD word."
removal = "BAD"
reverse_removal = removal[::-1]
replacement = "GOOD"
reverse_replacement = replacement[::-1]
newstr = mystr[::-1].replace(reverse_removal, reverse_replacement, 1)[::-1]
print ("mystr:", mystr)
print ("newstr:", newstr)
Output:
mystr: Remove last occurence of a BAD word. This is a last BAD word.
newstr: Remove last occurence of a BAD word. This is a last GOOD word.
If you know that the 'old' string does not contain any special characters you can do it with a regex:
In [44]: s = '<div><div>Hello</div></div>'
In [45]: import re
In [46]: re.sub(r'(.*)</div>', r'\1</bad>', s)
Out[46]: '<div><div>Hello</div></bad>'
Here is a recursive solution to the problem:
def rreplace(s, old, new, occurence = 1):
if occurence == 0:
return s
left, found, right = s.rpartition(old)
if found == "":
return right
else:
return rreplace(left, old, new, occurence - 1) + new + right
Try this:
def replace_last(string, old, new):
old_idx = string.rfind(old)
return string[:old_idx] + new + string[old_idx+len(old):]
Similarly you can replace first occurrence by replacing string.rfind() with string.find().
I hope it helps.
If you have a list of strings you can use list comprehension and string slicing in a one liner to cover the whole list.. No need to use a function;
myList = [x[::-1].replace('<div>'[::-1],'<bad>'[::-1],1)[::-1] if x.endswith('<div>') else x for x in myList]
I use if else to keep the items in the list that don't meet the criteria for replacement otherwise your list would just be the items that do meet the criteria.