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
Related
I thought that this code below could remove the trailing character of every element in a. I can't understand the output
a = ['wonderland#', 'alice,', 'in!$', 'book:']
for index, word in enumerate(a):
for ch in '#!$,:':
a[index] = word.strip(ch)
print(a)
>>>['wonderland#', 'alice,', 'in!$', 'book']
Recommended:
Try rstrip this way with a list comprehension:
a = ['wonderland#', 'alice,', 'in!$', 'book:']
print([i.rstrip('#!$,:') for i in a])
Or try regex:
import re
print([re.sub('[#!$,:]+$', '', i) for i in a])
Both codes output:
['wonderland', 'alice', 'in', 'book']
Not recommended:
The reason your code doesn't work is because you may well matched the character(s) at the end but the next iteration you would be still trying to strip from the original string, instead of the string that you just stripped in the previous iterations. Also you use strip so it might be that only one character would be striped, so you also need to use sorted, so to fix your code:
a = ['wonderland#', 'alice,', 'in!$', 'book:']
for index, word in enumerate(a):
for ch in sorted('#!$,:', key=word.find)[::-1]:
a[index] = a[index].strip(ch)
print(a)
print(a)
Output:
['wonderland', 'alice', 'in', 'book']
The problem is that you're iterating over the list and assigning it to word, then every call to strip starts over with the unmodified word. Try this instead:
for index in range(len(a)):
for ch in '#!$,:':
a[index] = a[index].strip(ch)
And it turns out that doesn't work either, because it's dependent on the order of the characters that you're removing. Take advantage of strips ability to remove multiple characters at once.
for index in range(len(a)):
a[index] = a[index].strip('#!$,:')
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]
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.'
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.
Consider this Python code for printing a list of comma separated values
for element in list:
print element + ",",
What is the preferred method for printing such that a comma does not appear if element is the final element in the list.
ex
a = [1, 2, 3]
for element in a
print str(element) +",",
output
1,2,3,
desired
1,2,3
>>> ','.join(map(str,a))
'1,2,3'
A ','.join as suggested in other answers is the typical Python solution; the normal approach, which peculiarly I don't see in any of the answers so far, is
print ','.join(str(x) for x in a)
known as a generator expression or genexp.
If you prefer a loop (or need one for other purposes, if you're doing more than just printing on each item, for example), there are of course also excellent alternatives:
for i, x in enumerate(a):
if i: print ',' + str(x),
else: print str(x),
this is a first-time switch (works for any iterable a, whether a list or otherwise) so it places the comma before each item but the first. A last-time switch is slightly less elegant and it work only for iterables which have a len() (not for completely general ones):
for i, x in enumerate(a):
if i == len(a) - 1: print str(x)
else: print str(x) + ',',
this example also takes advantage of the last-time switch to terminate the line when it's printing the very last item.
The enumerate built-in function is very often useful, and well worth keeping in mind!
It's very easy:
print(*a, sep=',')
Print lists in Python (4 Different Ways)
There are two options ,
You can directly print the answer using
print(*a, sep=',')
this will use separator as "," you will get the answer as ,
1,2,3
and another option is ,
print(','.join(str(x) for x in list(a)))
this will iterate the list and print the (a) and print the output as
1,2,3
That's what join is for.
','.join([str(elem) for elem in a])
print ','.join(a)
def stringTokenizer(sentense,delimiters):
list=[]
word=""
isInWord=False
for ch in sentense:
if ch in delimiters:
if isInWord: # start ow word
print(word)
list.append(word)
isInWord=False
else:
if not isInWord: # end of word
word=""
isInWord=True
word=word+ch
if isInWord: # end of word at end of sentence
print(word)
list.append(word)
isInWord=False
return list
print (stringTokenizer(u"привет парни! я вам стихами, может быть, еще отвечу",", !"))
>>> a=[1,2,3]
>>> a=[str(i) for i in a ]
>>> s=a[0]
>>> for i in a[1:-1]: s="%s,%s"%(s,i)
...
>>> s=s+","+a[-1]
>>> s
'1,2,3'