python string of a list weird output - python

How does the following output come?
>>> a
'hello'
>>> a = list(a)
>>> a
['h', 'e', 'l', 'l', 'o']
>>> a = str(a)
>>> a
"['h', 'e', 'l', 'l', 'o']"
>>> a.title()
"['H', 'E', 'L', 'L', 'O']"
>>> a[0]
'['
>>> a[1]
"'"
>>> a[2]
'h'
When title has to capitalize only the first letter of the string, how does every letter get capitalized?

str() does not join a list of individual characters back together into a single string. You'd use str.join() for that:
>>> a = list('hello')
>>> ''.join(a)
'hello'
str(listobject) returns a string representation of the list object, not the original string you converted to a list. The string representation is a debug tool; text you can, for the most part, paste back into a Python interpreter and have it recreate the original data.
If you wanted to capitalise just the first characters, use str.title() directly on the original string:
>>> 'hello'.title()
'Hello'
>>> 'hello world'.title()
'Hello World'

I think you're confused about how title works.
In [5]: s = "hello there"
In [6]: s.title()
Out[6]: 'Hello There'
See how it capitalises the first letter of each word? When you str() the list, it no longer sees hello as a single word. Instead, it sees each letter on its own and decides to capitalise each letter.

>>> a=list('hello')
>>> str(a)
"['h', 'e', 'l', 'l', 'o']"
>>> len(str(a))
25
So you have a string of 25 characters. All those ',, etc. are part of the string. title sees 5 one-character words, so each one is upper cased. Try ''.join instead
>>> ''.join(a)
'hello'
>>> len(''.join(a))
5
>>> ''.join(a).title()
'Hello'

Related

How do I change letters in this list in python?

So I'm trying to make a program that allows you to decode messages in python. Here's what I got so far...
def decode():
print("Let's see what she wanted to tell you.")
time.sleep(2)
messageOne= raw_input('Please paste the message: ')
print("Decoding message now...")
message= list(messageOne)
and I was wondering how I would take the individual letters in the list and change them based on the code I want. Aka I need to know how to change a specific value in the list. Thanks!
Your question isn't very clear, based on what I see you can have different ways of replacing letters. For example let's use string s:
>>> s = 'Hello'
>>> s.replace('l','h')
Hehho
If you only want to replace one occurrence of a given letter use this:
>>> s = 'Hello'
>>> s.replace('l','h', 1) #will only replace the first occurrence
Hehlo
You can also convert your string into a list
>>> s = 'Hello'
>>> s = [x for x in s]
>>> s
['H', 'e', 'l', 'l', 'o']
In here you can replace anything by anything, like so:
>>> s[3] = 'h'
>>> s
['H', 'e', 'l', 'h', 'o']
When you're done with replacing whatever you want, you can use the .join() method to make your list a string again like so:
>>> s = ''.join(s) #separator goes in between the quotes
>>> s
Helho

Comparing letters in list with string in a list python

I have a list lets say:
DIRECTION_LETTERS=['u', 'd' ,'r' , 'l', 'w', 'x', 'y', 'z']
Now the other parameter of mine is like arguement, I write in
udl and it returns ['udl']
so lets say another list arg_list = ['udl']
I want to check if u and d and l is in this list or i want to check if none of the letters in my direction letters list in the arg list
to make it print error msg I have tried this:
for letter in DIRECTION_LETTERS:
for char in arg_list[4]:
if letter in arg_list[4][0]:
continue
else:
print (ERROR_MESSAGE_DIRECTIONS)
return False
return True
There's a handy function in Python called all() which returns true if all arguments are true. Feel free to find a nice way of using it, but in general:
>>> DIRECTION_LETTERS=['u', 'd' ,'r' , 'l', 'w', 'x', 'y', 'z']
>>>
>>> s="udl"
>>> print(all(c in DIRECTION_LETTERS for c in s))
True
>>> s="udlxa"
>>> print(all(c in DIRECTION_LETTERS for c in s))
False
This line
if letter in arg_list[4][0]:
needs to be
if char in DIRECTION_LETTERS:
and you need to delete the line for letter in DIRECTION_LETTERS:.

Lists in Python targeting specific characters

I'm currently learning about lists in Python and I have a specific case that I don't really understand.
L=['hello','pie']
L[0][1]
'e'
Why does L[0][1] output as 'e'? I understand that L[0] = 'hello'. So I don't really understand how L[0][1] = 'e'.
Because you can also index strings in Python.
In [1]: L = ['hello', 'pie']
In [2]: L[0]
Out[2]: 'hello'
In [3]: 'hello'[1]
Out[3]: 'e'
In [4]: L[0][1]
Out[4]: 'e'
A string in python is treated as a sequence of characters for purposes of indexing. Thus the string 'hello' can be indexed as if it was the list ['h', 'e', 'l', 'l', 'o']. As the index [1] refers to the second item in a sequence, you'll get the second letter of the string, 'e'.

How to sort the letters in a string alphabetically in Python

Is there an easy way to sort the letters in a string alphabetically in Python?
So for:
a = 'ZENOVW'
I would like to return:
'ENOVWZ'
You can do:
>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
>>> a = 'ZENOVW'
>>> b = sorted(a)
>>> print b
['E', 'N', 'O', 'V', 'W', 'Z']
sorted returns a list, so you can make it a string again using join:
>>> c = ''.join(b)
which joins the items of b together with an empty string '' in between each item.
>>> print c
'ENOVWZ'
Sorted() solution can give you some unexpected results with other strings.
List of other solutions:
Sort letters and make them distinct:
>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower())))
' belou'
Sort letters and make them distinct while keeping caps:
>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s)))
' Bbelou'
Sort letters and keep duplicates:
>>> s = "Bubble Bobble"
>>> ''.join(sorted(s))
' BBbbbbeellou'
If you want to get rid of the space in the result, add strip() function in any of those mentioned cases:
>>> s = "Bubble Bobble"
>>> ''.join(sorted(set(s.lower()))).strip()
'belou'
Python functionsorted returns ASCII based result for string.
INCORRECT: In the example below, e and d is behind H and W due it's to ASCII value.
>>>a = "Hello World!"
>>>"".join(sorted(a))
' !!HWdellloor'
CORRECT: In order to write the sorted string without changing the case of letter. Use the code:
>>> a = "Hello World!"
>>> "".join(sorted(a,key=lambda x:x.lower()))
' !deHllloorW'
OR (Ref: https://docs.python.org/3/library/functions.html#sorted)
>>> a = "Hello World!"
>>> "".join(sorted(a,key=str.lower))
' !deHllloorW'
If you want to remove all punctuation and numbers.
Use the code:
>>> a = "Hello World!"
>>> "".join(filter(lambda x:x.isalpha(), sorted(a,key=lambda x:x.lower())))
'deHllloorW'
You can use reduce
>>> a = 'ZENOVW'
>>> reduce(lambda x,y: x+y, sorted(a))
'ENOVWZ'
the code can be used to sort string in alphabetical order without using any inbuilt function of python
k = input("Enter any string again ")
li = []
x = len(k)
for i in range (0,x):
li.append(k[i])
print("List is : ",li)
for i in range(0,x):
for j in range(0,x):
if li[i]<li[j]:
temp = li[i]
li[i]=li[j]
li[j]=temp
j=""
for i in range(0,x):
j = j+li[i]
print("After sorting String is : ",j)
Really liked the answer with the reduce() function. Here's another way to sort the string using accumulate().
from itertools import accumulate
s = 'mississippi'
print(tuple(accumulate(sorted(s)))[-1])
sorted(s) -> ['i', 'i', 'i', 'i', 'm', 'p', 'p', 's', 's', 's', 's']
tuple(accumulate(sorted(s)) -> ('i', 'ii', 'iii', 'iiii', 'iiiim', 'iiiimp', 'iiiimpp', 'iiiimpps', 'iiiimppss', 'iiiimppsss', 'iiiimppssss')
We are selecting the last index (-1) of the tuple

how to find special characters in a string

I have a code in Python and want to find vowels in a string.
The code I have written is following....I tried different combinations for using For-Loop, but it throws two different errors;
'int' object is not iterable,
string indices must be integers, not str.
how can I find all vowels in a line?
str1 = 'sator arepo tenet opera rotas'
vow1 = [str1[i] for i in str1 if str1[i] is 'a' | 'e' | 'o']
what about:
vowels = [ c for c in str1 if c in 'aeo' ]
You're getting errors because when you loop over a string, you loop over the characters in the string (not string indices) and because 'a' | 'e' | 'o' doesn't make sense for strings -- (they don't support the | operator)
>>> str1 = 'sator arepo tenet opera rotas'
>>> vowels = [ c for c in str1 if c in 'aeo' ]
>>> print vowels
['a', 'o', 'a', 'e', 'o', 'e', 'e', 'o', 'e', 'a', 'o', 'a']
One final comment, you shouldn't use is to test for equality. is tests for identity. A simple test:
a = 565
b = 565
print a == b #True
print a is b #False (!)
The reason is because a and b reference different objects that have the same value.
Try this code:
str1 = 'sator arepo tenet opera rotas'
i=0
vowl=''
for char in str1:
if char in 'aeiouAEIOU':
vowl=vowl+char+','
vowl=vowl[:-1]
print (vowl)
The output is:
a,o,a,e,o,e,e,o,e,a,o,a
In [1]: str1 = 'sator arepo tenet opera rotas'
In [2]: filter(lambda x: x in 'aeiou', str1)
Out[2]: 'aoaeoeeoeaoa'

Categories

Resources