Occurrence of nothing, not even space [duplicate] - python

This question already has answers here:
Why are str.count('') and len(str) giving different output?
(3 answers)
Closed 4 years ago.
I was going through something when i came across this...
a = 'hello'
print(a.count('l'))
print(a.count(''))
Output is :
2
6
Can anyone explain why the second output is 6 ?

count here returns the number of occurences of your substring, here a '' string.
There are indeed six '' in hello, between each char:
print(''.count('')) # >> 1
# You could symbolize it like that:
print('a'.count('')) # >> 2
# is equivalent to:
print('|a|'.count('|')) # >> 2

Related

How to check a string contains 3 dots in python [duplicate]

This question already has answers here:
Count the number of occurrences of a character in a string
(26 answers)
Closed 10 months ago.
eg: "ABC.sample.int.int01" like that, only want to check this string contains 3 dots.
Thanks
You can check it like this, with count attribute of str in python. If it is equal to 3, then your strings actually contains exactly 3 dots.
if 'ABC.sample.int.int01'.count('.') == 3:
...
else:
...

Why the result of “bag” > “apple” is True in Python? [duplicate]

This question already has answers here:
How are strings compared?
(7 answers)
Closed 2 years ago.
Why the result of “bag” > “apple” is True in Python?
I tried this code below i don't know why it show this result and how? Please some one explain it.
print("bag" > "apple")
True
I believe this is True because Python compares the first letter of each word. And b is greater than a in Python.

How to print output in Single line [duplicate]

This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed 3 years ago.
I want to know how to print output in a single line
I want to print it like: 1234
instead of
1
2
3
4
Code:
# n = (get in from user)
i=1
while (i<=n):
print (i,)
i +=1
This may help :
For Python 3:
print(i,end='')
For Python 2:
print(i),

Splitting a string into a list of numbers [duplicate]

This question already has answers here:
String of numbers to a list of integers?
(4 answers)
Closed 5 years ago.
The following block of code was tested on python 2.
A="1 2 10"
A=raw_input.split()
print A
This prints a list with 4 numbers(splitting the 10 into 1 and 0),
Why does this happen?
Just use normal split
B = A.split()

Printing integers in python list in correct orderly manner [duplicate]

This question already has answers here:
Pythonic way to check if a list is sorted or not
(27 answers)
Closed 6 years ago.
I have this list from user input:
sun=[8,8,7,7,4,6,4,5,]
>>> sun.index(8)
0
>>> sun.index(7)
2
>>> sun.index(4)
4
Would like to write a program to print "Impossible", because 4,5,6 are not in correct order in the list.
print "Impossible" * (sun != sorted(sun))

Categories