I want it to produce the number next to a word so that I can ask the user to select the word by using the corresponding number.
This is my code
alt_words = hlst
loopnum = 8
for i in range(loopnum):
if i < len(alt_words):
print('{0}. {1:<20}'.format((i+1), alt_words[i]), end =' ')
if i == 0:
print('', end=' ')
if i + 9 <= len(alt_words):
print('{0}. {1:<20}'.format((i+9), alt_words[i+8]), end =' ')
if i + 17 <= len(alt_words):
print('{0}. {1:<20}'.format((i+17), alt_words[i+16]), end=' ')
print('\n'+'-'*80)
It produces this
The first number of each line gets printed on the left, but the word on the right, while the rest of the numbers and words get printed RTL. It seems that once python has started printing on a line LTR it can switch to RTL, but not back from RTL to LTR. Note how even the periods are printed to the right of the number for the second set of numbers on each line.
It works perfectly well and looks nice with english words:
I am guessing a work around might involve putting the number after the word, but I figure there must be a better way.
Put a Right-to-Left Embedding character, u'\u202B', at the beginning of each Hebrew word, and a Pop Directional Formatting character, u'\u202C', at the end of each word.
This will set the Hebrew words apart as RTL sections in an otherwise LTR document.
(Note that while this will produce the correct output, you're also dependent on the terminal application in which you're running this script having implemented the Unicode Bidirectional Algorithm correctly.)
See Bi-directional (BiDi) layout implementation in pure python.
Install with:
pip install python-bidi
Example usage:
from bidi.algorithm import get_display
print(get_display('LTR text with RTL text (טקסט לדוגמא) will be printed correctly'))
The following package is also available if you are using Django:
http://pypi.python.org/pypi/django-bidi-utils
Related
I really want to know how python identifies # in quotes as a string and normal # as a comment
I mean how the code to identify difference between these actually works, like will the python read a line and how it excludes the string to find the comment
"# this is a string" # this is a comment
How the comment is identified, will python exclude the string and if so, How?
How can we write a code which does the same, like to design a compiler for our own language with python
I am a newbie, please help
You need to know that whether something is a string or a comment can be determined from just one single character. That is the job of the scanner (or lexical analyzer if you want to sound fancy).
If it starts with a ", it's a string. If it starts with #, it's a comment.
In the code that makes up Python itself, there's probably a loop that goes something like this:
# While there is still source code to read
while not done:
# Get the current character
current = source[pos]
# If the current character is a pound sign
if current == "#":
# While we are not at the end of the line
while current != "\n":
# Get the next character
pos += 1
current = source[pos]
elif current == '"':
# Code to read a string omitted for brevity...
else:
done = True
In the real Python lexer, there are probably dozens more of those if statements, but I hope you have a better idea of how it works now. :)
Because of the quotes
# This is a comment
x = "# this is a string"
x = '# this is a also string'
x = """# this string
spans
multiple
lines"""
"# this is a string" # this is a comment
In simple terms, the interpreter sees the first ", then it takes everything that follows as part of the string until it finds the matching " which terminates the string. Then it sees the subsequent # and interprets everything to follow as a comment. The first # is ignored because it is between the two quotes, and hence is taken as part of the string.
I have written a small tool that iterates over a wordlist and I want it to print each line from the wordlist over the previous line, I have tried the following but it has issues.
print(word + (100 * " "), end="\r", flush=True)
This works as expected in VSCodes in-built terminal but when I run the same tool in either the OS's (Xfce) in-built terminal or Terminator each "word" is printing on a newline
Does anyone know why this is happening all my research just points me on how to do it, which doesn't help as the way to do it is what has this issue.
Thanks
This is because depending on your window width (and word length), each string may be longer than the line. So the next print statement is 'overwriting' the previous string, but since that previous string jumped a line, so the new string starts on that new line.
You can see this in action by printing 99 spaces followed by a * or some other character:
print(word + (99 * " ") + "*")
Depending on your window width and word length, this may or may not jump a line, as demonstrated by where there "*" prints.
favoriteword = input('Enter your word: ')
print('What is your favorite word?',favoriteword)
print(favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword)
print(favoriteword, 'does not even sound like a word anymore.')
How can I make it so that in line 4 it comes out as "___" does not even sound like a word anymore." If I put it as this below it doesn't work.
print('"favoriteword"', 'does not even sound like a word anymore.')
Also if I put line 2 into a loop how would I print it so that it prints on a single line?
for i in range(12):
print(favoriteword)
In Python 2.6 or above, you can use string.format:
print('"{}" does not even sound like a word anymore.'.format(favoriteword))
In lower versions, Ketzak's method will work.
To print multiple times on a single line, you want to prevent print from appending a newline.
In Python 3, use the end argument:
for i in range(12):
print(favoriteword, end='')
print('') # for newline
or in lower versions:
import sys
for i in range(12):
sys.stdout.write(favoriteword)
print('')
Use the Python interpolation operator if you can guarantee favoriteword will always be a string:
print('"%s" does not even sound like a word anymore.' % favoriteword)
In python >= 3.6, you can use "f-string":
print(f'"{favoriteword}" does not even sound like a word anymore.')
See this link for more information about it.
I'm writing a text adventure in Python 2.7 and now want to make nice-looking output. I already tried to make a GUI with Tkinter, but it didn't work, because the user's text input could not be decoded in Tk, and I need it for German Umlauts. So now I'm trying to get good output straight in the Python shell or the Jupyter notebook. The problem is, when I do a print statement, I get output like:
This is a text and just a little exa
mple to show the problem.
But of course I don't want to get words stripped, like 'example'. It should look like this:
This is a text and just a little
example to show the problem.
I tired to work with the width of a display and thought that it would be good to split the string after 80 characters, but with the condition that it should only be split at a whitespace and not in a word. I wanted to do something like this:
def output(string):
for pos, char in enumerate(string):
if pos <= 80 and pos >=70 and char == " ":
templist = string.split(char)
...
Strings are immutable, so I think I have to convert it into a list, but then I don't know how to put the split-position of the string and the list together. Maybe I'm thinking too intricately.
Is there a way to say: If the string is longer than 80 characters, split the string at the nearest whitespace to the 80th character?
Use the textwrap module.
For example, if you want 40 character line width:
import textwrap
a = '''This is a text and just a little example to show the problem.'''
print("\n".join(textwrap.wrap(a,40)))
##This is a text and just a little example
##to show the problem.
I would look at the first 80 characters of a string and find the last occurrence of the space character, and then split your string there. You can use rfind() for this:
string = "This is a text and just a little example to show the problem"
lines = []
while string:
index = string[:80].rfind(' ')
if index == -1:
index = 80
lines.append(string[:index])
string = string[index:].lstrip()
I think you're looking for the textwrap module.
text_wrap.fill(your_text, width=your_width)
I am a beginner in python. I came across this question in codewars.
Jaden is known for some of his philosophy that he delivers via Twitter. When writing on Twitter, he is known for almost always capitalizing every word.
Your task is to convert strings to how they would be written by Jaden Smith. The strings are actual quotes from Jaden Smith, but they are not capitalized in the same way he originally typed them.
Example :
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased: "How Can Mirrors Be Real If Our Eyes Aren't Real"
This is my attempt (I am supposed to code using a function)
def toJadenCase(string):
l = len(string)
for i in range(0,l):
if string[i] == ' ':
y = string[i]
string[i+1] = chr(int(y)-32)
return srting
s = raw_input()
print toJadenCase(s)
When run, the following errors showed up
How can mirrors be real if our eyes aren't real (this is the input string)
Traceback (most recent call last):
File "jaden_smith.py", line 9, in <module>
print toJadenCase(s)
File "jaden_smith.py", line 6, in toJadenCase
string[i+1] = chr(int(y)-32)
ValueError: invalid literal for int() with base 10: ''
I couldn't understand these errors even after google-ing it. Any help would be appreciated. I would also be great if other errors in my code are highlighted and a better code is suggested.
Thanks in advance :D
As Goodies points out, string should not be used as a variable name
Following the Zen of Python, this is technically a function that does exactly what you're trying to achieve:
def toJadenCase(quote):
return quote.title()
Edit:
Revised version to deal with apostrophes:
import string
def toJadenCase(quote):
return string.capwords(quote)
First you have to understand that strings are immutable, so you cannot set a single character inside a string, but build a new string from the old one and replace the old one (this can be usually done still in one pass so it's not a big complication).
Second, for most of these kind of operations, it is much better to use the methods of the string object itself, rather than redo everything from scratch.
Said that, there is still some complication with the question, but a function that does what you want is in the module string:
import string
s="How can mirrors be real if our eyes aren't real"
newstring=string.capwords(s)
If you prefer (why?!) a DIY solution (using string methods):
newstring=' '.join([ss.capitalize() for ss in s.split()])
Note that using split without argument splits the string on any whitespace (e.g. tabs etc.), that I think is the desired behavior.
If you want to do this without using a function that already exists, this is how I would do it and I'll explain everything:
Assuming you get a string with ONLY text based words and all words start with a character*
def toJadenCase(string):
words = string.strip().split()
# This first strips all empty spaces around the words in the text and then splits the string by spaces (default) otherwise you can add a character inside split in order to split it at the character. This returns a list of words in the sentence.
li = [] # initialize empty list
for word in words:
word = chr(ord(word[0])-32) + word[1:]
# So there's a couple of things going on here.
# I could use .upper() to upper case something (like word[0].upper() + word[1:]
# in order to get it but I wanted to do it without the use of that.
# That being said, ord just figures out the ascii number and subtracting
# 32 makes it uppercase. chr changes it back to a string.
# Then it can be concatenated to the rest of the word.
# Strings can be treated as lists in python so word[0] and word[1:] works
Also, word[1:] just means from the 1st index to the end.
li.append(word) # this appends the word to the list
return ' '.join(li) # this joins all of the words in the list with a space
Now, if you want something a lot more concise (you can use .capitalize()):
def toJadenCaseShort(string):
return ' '.join([x.capitalize() for x in string.strip().split()])
which returns:
>>> abc("hello my friends")
'Hello My Friends'
Basically what it does is it uses list comprehension to strip and then split the words, capitalizes them, and then joins them with spaces!
Of course, you could just use string.title() as mark s. says but what's the fun in that? :)
Here is the answer that passed for me
import string
def toJadenCase(str):
quote = string.capwords(str)
return quote #Do not use print(quote) as it adds spaces
def toJadenCase(str):
quote = string.capwords(str)
return quote #Do not use print(quote) as it adds spaces