I have a string and I saved it inside a variable.
I want to change even characters to capitalize with for loop.
so i give my even characters and capitalized it. But
i cant bring them with odd characters .
can someone help me?
here is my code:
name = "mohammadhosein"
>>> for even in range(0, len(name), 2):
... if(even % 2 == 0):
... print(name[even].title(), end=' ')
...
M H M A H S I >>>
>>> ###### I want print it like this:MoHaMmAdHoSeIn```
I assume you are quite new to programing, so use a the following for loop:
name = "mohammadhosein"
output = ''
for i, c in enumerate(name):
if i % 2 == 0:
output += c.upper()
else:
output += c
# output will be 'MoHaMmAdHoSeIn'
enumerate will give you a pair of (i, c) where i is an index, starting at 0, and c is a character of name.
If you feel more comfortable with code you can use a list comprehension and join the results as follows:
>>> ''.join([c.upper() if i % 2 == 0 else c for i, c in enumerate(name)])
'MoHaMmAdHoSeIn'
As #SimonN has suggested, you just needed to make some small changes to your code:
for index in range(0, len(name)):
if(index % 2 == 0):
print(name[index].upper(), end='') # use upper instead of title it is more readable
else:
print(name[index], end='')
print()
Related
I have the list ['a','b','c','d','e','f','g']. I want to print it a certain way like this:
a b c
d e f
g
this is what I've tried:
result = ''
for i in range(len(example)):
result += example[i] + ' '
if len(result) == 3:
print('\n')
print(result)
but with this I continue to get one single line
Iterate over a range of indices and step by 3, creating slices of three elements at a time.
>>> a = ['a','b','c','d','e','f','g']
>>> for i in range(0, len(a), 3):
... print(a[i:i+3])
...
['a', 'b', 'c']
['d', 'e', 'f']
['g']
>>>
To format the data, you could either join the slice with ' ' or expand it out and use the sep argument to print.
>>> for i in range(0, len(a), 3):
... print(' '.join(a[i:i+3]))
...
a b c
d e f
g
>>> for i in range(0, len(a), 3):
... print(*a[i:i+3], sep=' ', end='\n')
...
a b c
d e f
g
>>>
The problem with the example code above is that len(result) will never be 3. result is always increased by a character plus a space, so its length will always be a multiple of 2. While you could adjust the check value to compensate, it will break if the list elements are ever more than 1 character.
Additionally, you don't need to explicitly print a "\n" in Python, as any print statement will automatically end with a new line character unless you pass a parameter to not do that.
The following takes a different approach and will work for any list, printing 3 elements, separated by spaces, and then printing a new line after every third element.
The end parameter of print is what should be added after the other arguments are printed. By default it is "\n", so here I use a space instead.
Once the index counter exceeds the list size, we break out of the loop.
i = 0
while True:
print(example[i], end=' ')
i += 1
if i >= len(example):
break
if i % 3 == 0:
print() # new line
Using enumerate
example = ['a','b','c','d','e','f','g']
max_rows = 3
result = ""
for index, element in enumerate(example):
if (index % max_rows) == 0:
result += "\n"
result += element
print(result)
I am making a UI for termux terminal on android.
This code below prints the content of the directory.
It works perfectly fine but the output is not even, ie, irregular spaces between the columns.
I've seen people using format but in my case the end argument value differ on each print.
def display_dir(dir_name):
direc = os.listdir(dir_name)
for index, d in enumerate(direc):
if index % 2 == 0:
print(f"{index}- {d}", end=" " * 10)
else:
print(f"{index}- {d}", end="\n")
but I want perfectly aligned 2 column output.I've tried many things. Is there a short way to do this?
I actually have a solution where I check the longest string and add white spaces for remaining strings but it's not optimal.
You are probably looking for something like this:
def display_dir(dir_name):
direc = os.listdir(dir_name)
max_len = len(max(direc, key=len))
for index, d in enumerate(direc):
if index % 2 == 0:
print("{:2}- {:<{}}".format(index, d, max_len), end=" ")
else:
print("{:2}- {:<{}}".format(index, d, max_len), end="\n")
Or even further:
def display_dir(dir_name):
direc = os.listdir(dir_name)
max_len_even = len(max(direc[::2], key=len))
max_len_odd = len(max(direc[1::2], key=len))
index_pad_len = len(str(len(direc)))
for index, d in enumerate(direc):
if index % 2 == 0:
print("{:{}}- {:<{}}".format(index, index_pad_len, d, max_len_even), end=" ")
else:
print("{:{}}- {:<{}}".format(index, index_pad_len, d, max_len_odd), end="\n")
I don't know why, but I am getting value of scope as final as 0 even len(s) as zero in the last line of countfrequency(s) function.
import collections
def countfrequency(s):
final = 0
flag = 1
d = dict(collections.Counter(s))
for item in d:
if d[item] <= k:
flag = 0
if flag == 1: #Here
final = max(final, len(s))
print(final)
s = "ababbc"
k = 2
for x in range(len(s)):
for y in range(1, len(s)):
countfrequency(s[x:y + 1])
It is because of 2 reasons :
Value of flag is 0 at last so it wont change the value of final
Length function takes object as a parameter and when unchanged it gives 0
So you can can either make flag 1 so that control goes inside if condition or print the value of len(s) out side the if condition
In addition to the answer posted by shaktiraj jadeja, the modified code is as follows:
import collections
def countfrequency(s, k):
final = 0
flag = 0
d = dict(collections.Counter(s))
# print(d)
for item in d:
if d[item] > k:
flag = 1
break
if flag == 1: #Here
# print("Inside:", final, len(s))
final = max(final, len(s))
print(final)
s = "ababbc"
k = 2
for x in range(len(s)):
for y in range(1, len(s)):
# print(s[x:y])
countfrequency(s[x:y + 1], k)
To start with there is no problem of scope.
Now lets get back to the problem
Lets define a rule.
Rule: If a sub string has each character repeated more than k(=2) times in it. Then it is a good substring. Else it is a bad substring
Then your code simply prints the length of good sub string or 0 in case of bad substring
In short in your example string s= "ababbc" contains no good substring
if you try S = "aaaaaa" you will see many numbers printed other than 0 (exactly 11 0's and 10 other numbers)
Now either this was your confusion or you wrote the wrong code for some logic
I hope this helps
I need a Python function which gives reversed string with the following conditions.
$ position should not change in the reversed string.
Should not use Python built-in functions.
Function should be an efficient one.
Example : 'pytho$n'
Result : 'nohty$p'
I have already tried with this code:
list = "$asdasdas"
list1 = []
position = ''
for index, i in enumerate(list):
if i == '$':
position = index
elif i != '$':
list1.append(i)
reverse = []
for index, j in enumerate( list1[::-1] ):
if index == position:
reverse.append( '$' )
reverse.append(j)
print reverse
Thanks in advance.
Recognise that it's a variation on the partitioning step of the Quicksort algorithm, using two pointers (array indices) thus:
data = list("foo$barbaz$$")
i, j = 0, len(data) - 1
while i < j:
while i < j and data[i] == "$": i += 1
while i < j and data[j] == "$": j -= 1
data[i], data[j] = data[j], data[i]
i, j = i + 1, j - 1
"".join(data)
'zab$raboof$$'
P.S. it's a travesty to write this in Python!
A Pythonic solution could look like this:
def merge(template, data):
for c in template:
yield c if c == "$" else next(data)
data = "foo$barbaz$$"
"".join(merge(data, reversed([c for c in data if c != "$"])))
'zab$raboof$$'
Wrote this without using any inbuilt functions. Hope it fulfils your criteria -
string = "zytho$n"
def reverse(string):
string_new = string[::-1]
i = 0
position = 0
position_new = 0
for char in string:
if char=="$":
position = i
break
else:
i = i + 1
j = 0
for char in string_new:
if char=="$":
position_new = i
break
else:
j = j + 1
final_string = string_new[:position_new]+string_new[position_new+1:position+1]+"$"+string_new[position+1:]
return(final_string)
string_new = reverse(string)
print(string_new)
The output of this is-
nohty$x
To explain the code to you, first I used [::-1], which is just taking the last position of the string and moving forward so as to reverse the string. Then I found the position of the $ in both the new and the old string. I found the position in the form of an array, in case you have more than one $ present. However, I took for granted that you have just one $ present, and so took the [0] index of the array. Next I stitched back the string using four things - The part of the new string upto the $ sign, the part of the new string from after the dollar sign to the position of the $ sign in the old string, then the $ sign and after that the rest of the new string.
I'm trying to count the number of differences between two imported strings (seq1 and seq2, import code not listed), but am getting no result when running the program. I want the output to read something like "2 differences." Not sure where I'm going wrong...
def difference (seq1, seq2):
count = 0
for i in seq1:
if seq1[i] != seq2[i]:
count += 1
return (count)
print (count, "differences")
You could do this pretty flatly with a generator expression
count = sum(1 for a, b in zip(seq1, seq2) if a != b)
If the sequences are of a different length, then you may consider the difference in length to be difference in content (I would). In that case, tag on an extra piece to account for it
count = sum(1 for a, b in zip(seq1, seq2) if a != b) + abs(len(seq1) - len(seq2))
Another weirdish way to write that which takes advantage of True being 1 and False being 0 is:
sum(a != b for a, b in zip(seq1, seq2))+ abs(len(seq1) - len(seq2))
zip is a python builtin that allows you to iterate over two sequences at once. It will also terminate on the shortest sequence, observe:
>>> seq1 = 'hi'
>>> seq2 = 'world'
>>> for a, b in zip(seq1, seq2):
... print('a =', a, '| b =', b)
...
a = h | b = w
a = i | b = o
This will evaluate similar to sum([1, 1, 1]) where each 1 represents a difference between the two sequences. The if a != b filter causes the generator to only produce a value when a and b differ.
When you say for i in seq1 you are iterating over the characters, not the indexes. You can use enumerate by saying for i, ch in enumerate(seq1) instead.
Or even better, use the standard function zip to go through both sequences at once.
You also have a problem because you return before you print. Probably your return needs to be moved down and unindented.
in your script there are to mistakes
"i" should be integer, not char
"return" should be in function the same level as print, not in cycle "for"
try not to use "print" in such way in functions
here is working version:
def difference (seq1, seq2):
count = 0
for i in range(len(seq1)):
if seq1[i] != seq2[i]:
count += 1
return (count)
So I had to do what you are asking to do and I came up with a very simple solution. Mine is a little different because I check the string to see which is bigger and put them in the correct variable for comparison later. All done with Vanilla python:
#Declare Variables
a='Here is my first string'
b='Here is my second string'
notTheSame=0
count=0
#Check which string is bigger and put the bigger string in C and smaller string in D
if len(a) >= len(b):
c=a
d=b
if len(b) > len(a):
d=a
c=b
#While the counter is less than the length of the longest string, compare each letter.
while count < len(c):
if count == len(d):
break
if c[count] != d[count]:
print(c[count] + " not equal to " + d[count])
notTheSame = notTheSame + 1
else:
print(c[count] + " is equal to " + d[count])
count=count+1
#the below output is a count of all the differences + the difference between the 2 strings
print("Number of Differences: " + str(len(c)-len(d)+notTheSame))
Correct code would be:
def difference(seq1, seq2):
count = 0
for i in range(len(seq1)):
if seq1[i] != seq2[i]:
count += 1
return count
First the return statement is done at the end of the function, therefore it should not be part of the for loop or the for loop would just run once.
Second the for loop wasn't correct because you weren't really telling giving the for loop an integer, therefore the correct code would be to give it a range the length of seq1, so:
for i in range(len(seq1)):