As the title says, I am confused on how to put back the string into a line after iterating through it.
Right now I have this:
for element in want_cyphered:
element = ord(element)
element = element + 13
element = chr(element)
print(element)
This iterates through the want_cyphered string and prints it. This is a function I'm using for a cipher and decipherer. What I was wondering is how to compile the iteration into an actual line again? Right now, my print is one character per line, but I want it to be all on one line. Any help would be appreciated! Using python.
The other answers aren't wrong, but since you're using Python, you may as well use what it's good at (and your code is likely to be faster as well):
want_cyphered = 'Some text'
cyphered = ''.join(chr(ord(ch) + 13) for ch in want_cyphered)
print(cyphered)
decyphered = ''.join(chr(ord(ch) - 13) for ch in cyphered)
print(decyphered )
To break that down (assuming you're new at Python): ''.join(list_of_parts) takes a list of string parts (characters or strings) and joins them together into a single string, using whatever the string at the start is - an empty string in this case.
You can generate that list of parts using a generator expression (a very well performing way of iterating over something iterable) like [ch for ch in some_str], which would get you a list of characters in a string.
I've put the generator in square brackets just now so that it would become an actual list, but when you only write a generator to use as the input to some function, you can just pass the generator itself, without the brackets like ''.join(ch for ch in some_str) - which basically does nothing. It takes the string apart and puts it back together again.
But you can apply operations to the elements of that generator as well, so instead of just ch, you could fill the list with chr(ord(ch) + 13) which is the cypher you were looking to apply.
Put all that together and you get:
cyphered = ''.join(chr(ord(ch) + 13) for ch in want_cyphered)
Create a variable and append your element to the variable inside the loop. When the loop ends print the result.
result = ""
for element in want_cyphered:
element = ord(element)
element = element + 13
element = chr(element)
result += element
print(result)
Or if you want to get really fancy...
print("".join([chr(ord(e) + 13) for e in want_cyphered]))
just do
for element in want_cyphered:
element = ord(element)
element = element + 13
element = chr(element)
print(element,end="")
the end="" part tells Python to add a empty string at the end. The end paramter defaults to a new line so it prints each character on one line. Setting end="" makes it all print on one line.
Just make an empty string and on each iteration, add the element to it!
want_cyphered = "Hello, World!"
cyphered = ""
for element in want_cyphered:
element = ord(element)
element = element + 13
element = chr(element)
# Add the element to string
cyphered += element
Here is an approach that uses the translate, make_trans functions.
from string import ascii_lowercase as lc, ascii_uppercase as uc
def rot_13(s):
return s.translate(str.maketrans(lc+uc, lc[13:]+lc[:13]+uc[13:]+uc[:13]))
s = 'Hello World!'
print(rot_13(s))
Prints
Uryyb Jbeyq!
Related
I am making a decode method, which selects a set of index values within strings to remove. But right now the problem is i am unable to understand how to select a set of indices to remove
I have tried making a list of items to designate and remove if found in the string, but this would only work for only a few types of string sets.
def decode(string, n):
for i in range(0,len(string), n):
string = string.replace(string[i],'')
return string
here n is the number of values to remove at a given index as well as the index from where to start removing the said values
I understand how to step through an index, but I am not sure how to remove string values according to the index.
print(decode('#P#y#t#h#o#n#',1)) #this works out to be Python
print(decode('AxYLet1x3’s T74codaa7e!',3 )) #this does not, this is supposed to be 'Let's Code'
With "switcher" flag:
def decode(inp_str, n):
s = ''
flag = True
for i in range(0, len(inp_str), n):
flag = not flag
if flag: s += inp_str[i: i + n]
return s
print(decode('#P#y#t#h#o#n#', 1)) # Python
print(decode('AxYLet1x3’s T74codaa7e!', 3)) # Let’s code!
Different approach would be to pick the characters at the right positions:
def decode(string, n):
res = ''
for i in range(len(string)//(2*n)+1):
res += string[2*n*i+n:2*n*i+2*n]
return res
Don't change the size of an iterable when going through it!
The best would be to replace the character with some placeholder that can't be in the string, and then stripping it.
E.g. for your first example you already have that string format. Removing them outside the loop (remember, loop is for marking the characters for deletion) would be:
return ''.join(c for c in string if c!='#')
As for the loop itself in this approach, I'll leave it up to you to debug it now. ;) See how index moves in the loop, see what your replace in fact does! E.g. as I said in the comment, n=1 would go through literally every character, not every second character!
Another solution is smart slicing with indexes. Assuming from your examples that you want to 'remove n, keep n' code:
def decode(string, n):
result = ""
for i in range(n,len(string), 2*n): # first index we want to keep is n, next is 3n, 5n... so we're jumping by 2n each time
result += string[i: i+n]
return result
First, you're returning right after the first iteration. Second, you're only replacing character at n'th position with "".
This should do what you require, it'll replace every 'n' number of characters after every 'n' index:
def decode(string, n):
for i in range(0,len(string)-1,n):
string = string[:i] + string[i+n:] # Remove elements at index "i", till "i+n"
return string
Output:
print(decode('#P#y#t#h#o#n#',1)) # Output = Python
print(decode('AxYLet1x3’s T74codaa7e!',3 )) # Output = Let's Code
def password(passlist):
listt = []
for i in range(0, len(passlist)):
temp = passlist[i]
for j in range(0, len(temp)/2):
if((j+2)%2 == 0) :
t = temp[j]
temp.replace(temp[j], temp[j+2])
temp.replace(temp[j+2], t)
listt.append(temp)
I am passing a list of string
example ["abcd", "bcad"]. for each string i will swap ith character with j character if (i+j)%2 == 0.
My code is going out of the boundary of string.
Please suggest me a better approach to this problem
Here's how I'd do it:
def password(passlist):
def password_single(s):
temp = list(s)
for j in range(0, len(temp) // 2, 2):
temp[j], temp[j+2] = temp[j+2], temp[j]
return ''.join(temp)
return [password_single(s) for s in passlist]
print(password(["abcd", "bcad"]))
Define a function that operates on a single list element (password_single). It's easier to develop and debug that way. In this case, I made it an inner function but it doesn't have to be.
Use three-argument range calls, since it's the same as doing the two-argument + if(index%2 == 0)
Convert strings to lists, perform the swapping and convert back.
Use a "swap" type operation instead of two replaces.
Strings are immutable in python, therefore you cannot swap the characters in place. You have to build a new string.
Moreover, your code does not work for each string in passlist. You iterate through the string in passlist in the first for block, but then you use the temp variable outside that block. This means that the second for loop only iterates on the last string.
Now, a way to do what you want, might be:
for i in range(len(passlist)):
pass_ = passlist[i]
new_pass = [c for c in pass_] # convert the string in a list of chars
for j in range(len(pass_) / 2):
new_pass[j], new_pass[j+2] = new_pass[j+2], new_pass[j] # swap
listt.append(''.join(new_pass)) # convert the list of chars back to string
I am new to python and i'm stuck on a simple task. I want to print a range of number on the same line, with a "+" between each of them. This is the best I've been able to do so far, but obviously there is an extra "+" at the end of my line.
for i in range (1,10):
print (i , end="+")
Output:
1+2+3+4+5+6+7+8+9+
Simple one-line solution:
result = "+".join(str(i) for i in range(1, 10))
You can use the built-in join() method to insert a delimiter between each item in a list. In this case, the delimiter is +. We pass the iterable generated by range as the argument, converting each number into a string via the looping construct.
EDIT: If you need to use iteration for this, I'd go with the following approach:
result = ""
for i in range(1, 10):
result += str(i) + "+"
print(result[:-1])
Basically we create an empty string, append each number and a + sign to it, and then remove the last character using the slice.
If you cannot use anything list-related, then the easiest approach would be to stop the loop before the final number and add it manually.
result = ""
for i in range(1, 9):
result += str(i) + "+"
print(result + "9")
If you just need to print the values, you could unpack the sequence returned by range() and pass a custom separator to print():
>>> print(*range(1, 10), sep="+")
1+2+3+4+5+6+7+8+9
Shortest and arguably most-readable snippet I can think of:
print('+'.join(map(str, range(1, 10)))) # -> 1+2+3+4+5+6+7+8+9
so far this is my code
def firstChars( s ):
for word in s:
print (s[0][0])
this is what it prints:
>>> s='hello','world'
>>> firstChars(s)
h
h
how do i alter this code so that it prints out 'h' and 'w'?
s[0] will always be the first element in the sequence passed to the function. In order to use the specific word being examined in the for loop just above, use word within the loop instead.
word represents each element of the tuple/iterable. For the tuple ("Hello", "World"), word will be equal to "Hello" then "World". To get the first letter of each, subscript the word: word[0].
Note that this isn't the safest approach, as it will crash on an empty string (because "" doesn't have a 0-th element). I might define a "firstLetter" function that deals with the cases of an empty string if you can't guarantee that the string won't be empty.
To elaborate on JL's answer, what you wrote runs "fine" because Strings and tuples are both iterable (like a list).
When you wrote s[0][0], s[0] evaluated to "Hello", then you're left with "Hello"[0], which evaluates to 'H'. It output twice, once for each loop iteration because you based the loop on the tuple, which had 2 elements.
Alternative pythonic way
s='hello','world'
print('\r\n'.join(item[0] for item in s))
h
w
with the for word in s loop, word will first point to the first element of s, then to the second etc. If the explanation doesn't make sense to you, just run this:
def each_word(s):
for word in s:
print s
s = ("hello", "wolrd")
each_word(s)
Now the first char of a string word is word[0], and this should be enough to solve your problem.
for word in s:
print (s[0][0])
in this code fragment word becomes each element of s in turn -- s[0] ('hello') then s[1] ('world'). Whereas s[0][0] directly accesses the first element of the first element of s ('h'). you are looking to access the first element of each element in turn. So:
for word in s:
print (word[0])
will do what you are trying to accomplish.
This works. Now, one bit of warning, and it goes back to another comment about naming. In Python, it can be very hard to distinguish a string from a list or a tuple. They all iterate, they all have lengths and indices.
Be careful in how you name things, because there is no compiler to catch goofups.
def firstChars( s ):
#iterate through list/tuple passed in
for word in s:
#now, pick the first character
print (word[0])
Try this:
def firstChars( s ):
for word in s:
print (word[0])
In the function firstChars, you correctly loop over the items in s, but note that inside the for block, you should use word as that is the variable that is assigned the current item in s.
Also note that when you have multiple indices lined up as ins[0][0], each one "digs deeper" into the previous item. So, s[0] refers to the first item in s (the string 'hello'), the following [0] refers to the first char of that item ('h').
def main():
string = raw_input("string:")
pattern = raw_input("pattern:")
end = len(string)
insertPattern(string,pattern)
def insertPattern(string,pattern):
end= len(string)-1
print "Iterative:",
for x in range(end):
if x == end:
print string[x]
if x < end:
print string[x]+pattern,
main()
I'd like this to output
Instead it's outputting
How would I modify the code to fix this? Assignment requires that I do this without lists or join.
You've got three problems here.
First, the reason you're getting that Iterative: at the beginning is because you explicitly asked for it with this line:
print "Iterative:",
Just take it out.
The reason you're getting spaces after each * is a bit trickier. The print statement's "magic comma" always prints a space. There's no way around that. So, what you have to do is not use the print statement's magic comma.
There are a few options:
Use the more-powerful print function from Python 3.x, which you can borrow in 2.7 with a __future__ statement. You can pass any separator you want to replace the space, even the empty string.
Use sys.stdout.write instead of print; that way you get neither newlines nor spaces unless you write them explicitly.
Build up the string as you go along, and then print the whole thing at the end.
The last one is the most general solution (and also leads to lots of other useful possibilities, like returning or storing the built-up string), so I'll show that:
def insertPattern(string,pattern):
result = ''
end= len(string)-1
for x in range(end):
if x == end:
result += string[x]
if x < end:
result += string[x]+pattern
print result
Finally, the extra * at the end is because x == end can never be true. range(end) gives you all the numbers up to, but not including end.
What you probably wanted was end = len(string), and then if x == end-1.
But you can simplify this quite a bit. The only reason you need x is to get string[x], and to distinguish either the first or last value from the others (so you know not to add an extra * either before the first or after the last). You can solve the last one with a flag, or by just treating the first one special. And then, you can just iterate over string itself, instead of over its indices:
def insertPattern(string,pattern):
result = string[0]
for ch in string[1:]:
result += pattern + ch
print result
And once you've done that, you may realize that this is almost identical to what the str.join method does, so you can just use that:
def insertPattern(string,pattern):
print pattern.join(string)