I've made a simple script in python which shifts the letters up 5 spaces in the ASCII table using chr and ord. See below:
word = "python"
print 'Shifted 5 letters are: '
for letters in word:
print chr(ord(letters)+5),
The output is:
Shifted 5 letters is:
u ~ y m t s
The output is great, but how do I stop the for loop putting spaces in-between each letter?
If you don't need to use the for loop, simply do this:
print ''.join([chr(ord(letter) + 5) for letter in word])
instead of the whole loop.
There is no way to stop Python 2.x's print statement from printing a space when you use the "magic comma".
This is part of the reason Python 3.x's print function is more flexible, using keyword arguments instead of magic syntax:
for letters in word:
print(chr(ord(letters)+5), end='')
If you really want to, you can get the same behavior in Python 2.x with from __future__ import print_function (or by using the third-party six library).
However, usually, when you're having problem fighting with print to do what you want, the solution is to format your string first, then print it. So:
output = ''
for letters in word:
output += chr(ord(letters)+5)
print output
It's generally more pythonic (and faster) to build up a list of strings, and calling join at the end, instead of repeatedly appending to a string:
output = []
for letters in word:
output.append(chr(ord(letters)+5))
print ''.join(output)
And you can make that simpler (and even more fasterer) by turning the loop into a comprehension instead of a statement:
print ''.join(chr(ord(letters) + 5) for letters in word)
I don't know if I get what you're asking 100 % but this work-around returned the letters without any whitespace :
def no_space(word) :
new_word = ""
for letter in word :
new_word += chr(ord(letter) + 5)
return new_word
Then call the function :
no_space("python")
Result : 'u~ymts'
Related
How would I take the results from the following code and assign a variable to it?
for I in word: print (I + 117)
For example, if the results came out to be 100,101,102,103 how would I get a variable set to "100,101,102,103" without manually entering every number into a variable. Also, I know that it says "your encrypted string is" and I know that that's not really encrypted, but I just got into this so I was just playing around.
word = eval(input("What would you like to say"))
print (word)
encrypt = 117
print ("Your encrypted string is:")
for I in word:
print (I + 117)
assuming I have ASCII codes set to their appropriate values
Thanks to many people (most notably yukashima huksay and ZYYYY) I have my final code here:
word = eval(input("What would you like to say"))
print (word)
changedword = (', '.join(str(I + 15) for I in word))
print ("Your encrypted string is:" + changedword)
Assuming all ASCII codes set as variables.
You should do this:
a = ','.join([x for x in word])
Please note that you can use any string instead of ',' for example ', ' or '\n' or basically whatever you can store in a string.
You can also put a function of x instead like [foo(x) for x in word] or (2*x + 1)
And finally you can also use in-line if/else statements like:
[foo(x) if x>1 else bar(x) for x in word]
And also:
[foo(x) for x in word if x is not None]
The error you are getting is because you are adding a number to a character perhaps what you want to do is:
word = 'mokhlesim'
shift = 117
print(','.join([chr(ord(x)+shift) for x in word]))
result: è,Ö,á,Ö,â
str.join(iterable) would give you what you want.
I don't think eval() is a good practice here. word = input("somethin") is enough for python3.
Also you may want to know about list comprehensions which makes code more concise.
eval(exp) is to use to parse and evaluate exp as a python expression. For example
x = 1
a = eval("x + 1")
print(a)
#should print 2
I think you may want something like
word = input("give me something\n")
a = ','.join([chr(ord(c) + 117) for c in word])
print(a)
#if i type in here, it should print "Ý,Ú,ç,Ú"
I'm working with a hangman like project whereas if the user inputs a letter and matches with the solution, it replaces a specific asterisk that corresponds to the position of the letter in the solution. I'm trying to do this by getting the index of the instance of that letter in the solution then replacing the the matching index in the asterisk.
The thing here is that I only get the first instance of a recurring character when I used var.index(character) whereas I also have to replace the other instance of that letter. Here's the code:
word = 'turtlet'
astk = '******'
for i in word:
if i == t:
astk[word.index('i')] = i
Here it just replaces the first instance of 't' every time. How can I possibly solve this?
index() gives you only the index of the first occurrence of the character (technically, substring) in a string. You should take advantage of using enumerate(). Also, instead of a string, your guess (hidden word) should be a list, since strings are immutable and do not support item assignment, which means you cannot reveal the character if the user's guess was correct. You can then join() it when you want to display it. Here is a very simplified version of the game so you can see it in action:
word = 'turtlet'
guess = ['*'] * len(word)
while '*' in guess:
print(''.join(guess))
char = input('Enter char: ')
for i, x in enumerate(word):
if x == char:
guess[i] = char
print(''.join(guess))
print('Finished!')
Note the the find method of the string type has an optional parameter that tells where to start the search. So if you are sure that the string word has at least two ts, you can use
firstindex = word.find('t')
secondindex = word.find('t', firstindex + 1)
I'm sure you can see how to adapt that to other uses.
I believe there's a better way to do your specific task.
Simply keep the word (or phrase) itself and, when you need to display the masked phrase, calculate it at that point. The following snippet shows how you can do this:
>>> import re
>>> phrase = 'My hovercraft is full of eels'
>>> letters = ' mefl'
>>> display = re.sub("[^"+letters+"]", '*', phrase, flags=re.IGNORECASE)
>>> display
'M* ***e****f* ** f*ll *f eel*'
Note that letters should start with the characters you want displayed regardless (space in my case but may include punctuation as well). As each letter is guessed, add it to letters and recalculate/redisplay the masked phrase.
The regular expression substitution replaces all characters that are not in letters, with an asterisk.
for i in range(len(word)):
if word[i] == "t":
astk = astk[:i] + word[i] + astk[i + 1:]
This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
I'm new to coding, and I found this exercise problem in a Python practice website. The instructions go like this:
"Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
So I inputted this code:
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter)
else:
print(letter+'o'+letter)
print(translate('this is fun'))
and I got this:
tot
hoh
i
sos
o
i
sos
o
fof
u
non
None
So how do I put all these strings in one line? I've been scratching my head for so long. Please help and thank you:)
You can concatenate the strings iteratively. You should include a whitespace as part of the characters to exclude to avoid putting an 'o' in between whitespaces.
def translate(string):
notconsonant = ['a','e','i','o','u', ' ']
s = ''
for letter in string:
if letter in notconsonant:
s += letter
else:
s += letter+'o'+letter
return s
Or use join with a generator expression that returns the right letter combination via a ternary operator:
def translate(string):
notconsonant = {'a','e','i','o','u', ' '}
return ''.join(letter if letter in notconsonant else letter+'o'+letter for letter in string)
Note that you can speed up the lookup of letters that are not consonants if you made the list a set, as membership check for sets is relatively faster.
>>> translate('this is fun')
'tothohisos isos fofunon'
Just use the end parameter in print function. (I assumed that you are using python 3.x, with print being a function)
def translate(string):
vowels=['a','e','i','o','u']
for letter in string:
if letter in vowels:
print(letter, end='')
else:
print(letter+'o'+letter, end='')
print(translate('this is fun'))
Try to append it in a temporary string and to print it at the end ;)
print get's you to a new line. Use a concatenation and a new string instead (here the new string is called result) :
def translate(string):
vowels=['a','e','i','o','u']
# Use a new variable :
result = ''
for letter in string:
if letter in vowels:
result = result + letter
else:
result = result + letter + 'o' + letter
return result
print(translate('this is fun'))
I'm trying to make a program using python for class that works like this:
'Enter a word: " (EG Stack)
Then it outputs
S
St
Sta
Stac
Stack
I believe that it would use a looping function, but I'm completely stuck!
You can use slicing to achieve your output. Each iteration of the for loop increments an index variable (i below), and this is used to display ever increasing slices from the string.
>>> word = 'Stack'
>>> for i in range(1, len(word)+1):
... print word[:i]
...
S
St
Sta
Stac
Stack
>>> word='Slicing'
>>> for i in range(1, len(word)+1):
... print word[:i]
...
S
Sl
Sli
Slic
Slici
Slicin
Slicing
You can read about slicing in the Python tutorial.
msg = raw_input("Enter a word: ") #raw_input will convert the input into a string
#otherwise it would crash without quotation marks
word = "" #Initialize a variable
for letter in msg: #Cycle through each letter
word += letter #Adds that letter to your string
print(word) #Prints out the current letters
http://pastebin.com/CDzNfdbJ
Got it, I don't really understand it, but it works.
I have a homework question which asks to read a string through raw input and count how many vowels are in the string. This is what I have so far but I have encountered a problem:
def vowels():
vowels = ["a","e","i","o","u"]
count = 0
string = raw_input ("Enter a string: ")
for i in range(0, len(string)):
if string[i] == vowels[i]:
count = count+1
print count
vowels()
It counts the vowels fine, but due to if string[i] == vowels[i]:, it will only count one vowel once as i keeps increasing in the range. How can I change this code to check the inputted string for vowels without encountering this problem?
in operator
You probably want to use the in operator instead of the == operator - the in operator lets you check to see if a particular item is in a sequence/set.
1 in [1,2,3] # True
1 in [2,3,4] # False
'a' in ['a','e','i','o','u'] # True
'a' in 'aeiou' # Also True
Some other comments:
Sets
The in operator is most efficient when used with a set, which is a data type specifically designed to be quick for "is item X part of this set of items" kind of operations.*
vowels = set(['a','e','i','o','u'])
*dicts are also efficient with in, which checks to see if a key exists in the dict.
Iterating on strings
A string is a sequence type in Python, which means that you don't need to go to all of the effort of getting the length and then using indices - you can just iterate over the string and you'll get each character in turn:
E.g.:
for character in my_string:
if character in vowels:
# ...
Initializing a set with a string
Above, you may have noticed that creating a set with pre-set values (at least in Python 2.x) involves using a list. This is because the set() type constructor takes a sequence of items. You may also notice that in the previous section, I mentioned that strings are sequences in Python - sequences of characters.
What this means is that if you want a set of characters, you can actually just pass a string of those characters to the set() constructor - you don't need to have a list one single-character strings. In other words, the following two lines are equivalent:
set_from_string = set('aeiou')
set_from_list = set(['a','e','i','o','u'])
Neat, huh? :) Do note, however, that this can also bite you if you're trying to make a set of strings, rather than a set of characters. For instance, the following two lines are not the same:
set_with_one_string = set(['cat'])
set_with_three_characters = set('cat')
The former is a set with one element:
'cat' in set_with_one_string # True
'c' in set_with_one_string # False
Whereas the latter is a set with three elements (each one a character):
'c' in set_with_three_characters` # True
'cat' in set_with_three_characters # False
Case sensitivity
Comparing characters is case sensitive. 'a' == 'A' is False, as is 'A' in 'aeiou'. To get around this, you can transform your input to match the case of what you're comparing against:
lowercase_string = input_string.lower()
You can simplify this code:
def vowels():
vowels = 'aeiou'
count = 0
string = raw_input ("Enter a string: ")
for i in string:
if i in vowels:
count += 1
print count
Strings are iterable in Python.
for i in range(0, len(string)):
if string[i] == vowels[i]:
This actually has a subtler problem than only counting each vowel once - it actually only tests if the first letter of the string is exactly a, if the second is exactly e and so on.. until you get past the fifth. It will try to test string[5] == vowels[5] - which gives an error.
You don't want to use i to look into vowels, you want a nested loop with a second index that will make sense for vowels - eg,
for i in range(len(string)):
for j in range(len(vowels)):
if string[i] == vowels[j]:
count += 1
This can be simplified further by realising that, in Python, you very rarely want to iterate over the indexes into a sequence - the for loop knows how to iterate over everything that you can do string[0], string[1] and so on, giving:
for s in string:
for v in vowels:
if s == v:
count += 1
The inner loop can be simplified using the in operation on lists - it does exactly the same thing as this code, but it keeps your code's logic at a higher level (what you want to do vs. how to do it):
for s in string:
if s in vowels:
count += 1
Now, it turns out that Python lets do math with booleans (which is what s in vowels gives you) and ints - True behaves as 1, False as 0, so True + True + False is 2. This leads to a one liner using a generator expression and sum:
sum(s in vowels for s in string)
Which reads as 'for every character in string, count how many are in vowels'.
you can use filter for a one liner
print len(filter(lambda ch:ch.lower() in "aeiou","This is a String"))
Here's a more condensed version using sum with a generator:
def vowels():
string = raw_input("Enter a string: ")
print sum(1 for x in string if x.lower() in 'aeiou')
vowels()
Option on a theme
Mystring = "The lazy DOG jumped Over"
Usestring = ""
count=0
for i in Mystring:
if i.lower() in 'aeiou':
count +=1
Usestring +='^'
else:
Usestring +=' '
print (Mystring+'\n'+Usestring)
print ('Vowels =',count)
The lazy DOG jumped Over
^ ^ ^ ^ ^ ^ ^
Vowels = 7