Print a string in python like how dot-matrix printer works - python-3.x

I wanted to print any English alphabet(s) using '*' or any other given special character like how a dot-matrix printer works.
I could come up with a function def printLetters(string, font_size, special_char): which when passed with any letter would print that letter using the special character specified.
Consider the letter 'A':
def printLetters('A', 10, '&'): # would print the letter A within a 10x10 matrix using '&'
&&&&&&&&
& &
& &
& &
&&&&&&&&&&
& &
& &
& &
& &
& &
and such code snippets for every character.
Example for 'A':
FUNCTION_TO_PRINT_A:
space = ' '
#print first line
print('', special_char*(font_size-2))
for i in range(1, font_size-1):
#print(i)
if font_size//2 == i:
print(special_char*(font_size))
print(special_char, space*(font_size-2), special_char, sep = '')
printLetters('A', 10, "&")
But when the parameter string has more than one characters, it prints gibberish after first character.
So I just wanted some ideas/code-snippets which would print the first row of all characters in string first and so on until the last row so that all those characters line up side by side horizontally on the console.

Ah, fond memories. We used to do this sort of thing all the time in the olden days before GUIs. It is good that you want to define the shape of each letter separately, but making a separate function to print each letter is obviously not useful. After you print the N lines of one letter, you have no way to get back to the top.
You know that you need to print the top line of ALL letters, then the 2nd line of ALL letters, etc. I don't want to write you a complete example, because it's pretty important for you to learn how to figure this kind of thing out, but why don't you start with something like this:
font = {
'A': [
' ### ',
'# # ',
'##### ',
'# # ',
'# # '
],
'B': [
'#### ',
'# # ',
'#### ',
'# # ',
'#### '
],
...etc...
}

Related

Move a character or word to a new line

Given a string how do i move part of the string in to a new line. without moving the rest of the line or characters
'This' and 'this' word should go in the next line
Output:
> and word should go in the next line
This this
This is just an example of the output i want assuming the words can be different by characters. To be more clear say i have some string elements in an array and i have to move every second and third word of the elements to a new line and printing the rest of the line as is. I've tried using \n and a for loop. But it also moves the rest of the string to a new line
['This and this', 'word should go', 'in the next']
Output:
> This word in
and this should go the next
So the 2nd and 3rd word of the elements are moved without affecting the rest of the line. Is it possible to do this without much complication? I'm aware of the format method but i don't know how to use it in this situation.
For your first example, in case you don't know the order of the target words in advance, I would use a dictionary to store the indices of the found words. Then you can sort those to put the found words in the second line in the same order as they appeared in the text:
targets = ['this', 'This']
source = 'This and this word should go in the next line.'
target_ixs = {source.find(target): target for target in targets}
line2 = ' '.join([target_ixs[i] for i in sorted(target_ixs)])
line1 = source
for target in targets:
line1 = line1.replace(target, '')
line1 = line1.replace(' ', ' ').lstrip()
result = line1 + '\n' + line2
print(result)
and word should go in the next line.
This this
Your second example is easier, because you already know which parts of the strings to put in the second line, so you just need to split each string into a list of words and select from those:
source = ['This and this', 'word should go', 'in the next']
source_lists = [s.split() for s in source]
line1 = ' '.join([source_list[0] for source_list in source_lists])
line2 = ' '.join([' '.join(source_list[1:]) for source_list in source_lists])
result = line1 + '\n' + line2
print(result)
This word in
and this should go the next
You can probably do quite a bit without much complication using the regular expression library and some python language features. That being said, it depends on how complex the rules are for determining what words go where. Typically, you want to start with a string and "tokenize" it into the constituent words. See the code example below:
import re
sentence = "This and this word should go in the next line"
all_words = re.split(r'\W+', sentence)
matched_words = " ".join(re.findall(r"this", sentence, re.IGNORECASE))
unmatched_words = " ".join([word for word in all_words if word not in matched_words])
print(f"{unmatched_words}\n{matched_words}")
> and word should go in the next line
This this
Final Thoughts:
I am by no means a regex ninja so, there may be even more clever things that can be done with just regex patterns and functions. Hopefully, this gives you some food for thought at least.
Got it:
data = ['This and this', 'word should go', 'in the next']
first_line = []
second_line = []
for item in data:
item = item.split(' ')
first_word = item[0]
item.remove(first_word)
others = " ".join(item)
first_line.append(first_word)
second_line.append(others)
print(" ".join(first_line) + "\n" + " ".join(second_line))
My Solution:
input_data = ['This and this', 'word should go ok', 'this next']
I've slightly altered your test string to better test the code.
# Example 1
# Print all words in input_data, moving any word matching the
# string "this" (match is case insensitive) to the next line.
print('Example 1')
lines = ([], [])
for words in input_data:
for word in words.split():
lines[word.lower() == 'this'].append(word)
result = ' '.join(lines[0]) + '\n' + ' '.join(lines[1])
print(result)
The code in example 1 sorts each word into the 2-element tuple, lines. The key part is the boolean expression that preforms the string comparison.
# Example 2
# Print all words in input_data, moving the second and third
# word in any string to the next line.
from itertools import count
print('\nExample 2')
lines = ([], [])
for words in input_data:
for q in zip(count(), words.split()):
lines[q[0] in (1, 2)].append(q[1])
result = ' '.join(lines[0]) + '\n' + ' '.join(lines[1])
print(result)
The next solution is basically the same as the first. I zip each word to an integer so you know the word's position when you get to the boolean expression which, again, sorts the words into their appropriate list in lines.
As you can see, this solution is fairly flexible and can be adjusted to fit a number of scenarios.
Good luck, and I hope this helped!

What happens in this while loop in python

So I learnt the second course of python on edx and here is a code I wrote but don't really understand the part in the while loop. Could someone explain to me like I'm 6 years old what happens there?
Code:
# [ ] Print each word in the quote on a new line
quote = "they stumble who run fast"
start = 0
space_index = quote.find(" ")
while space_index != -1: #the code in while needs to be explained to me
print(quote[start:space_index])
start = space_index +1
space_index = quote.find(" ", space_index +1)
Your code attempts to demonstrate how to retrieve a sub-string from a string by index in Python, using a while loop having as stop condition that index.
The Python documentation on the function find() of string is here. Quoting from it:
The steps are these:
How to retrieve the index of the first occurrence of a given character in the string quote. In this line: quote.find(" "), it returns the index of the first position of a whitespace. So space_index will be equal to 4 when the while loop begins.
How to retrieve a sub-string from the string. In this line: quote[start:space_index] if you translate the variables start and space_index, what you have is: quote[0,4] which is equal to "they" in the first iteration.
How to increment the index. At the end of the while, you again do quote.find(" ", space_index +1) trying to get the index of a whitespace " ". But this time the position you start to search from is space_index+1 which on the first iteration will be 5. The function quote.find will return the value 12.
So in the 2nd iteration of the while: you'll be trying to get the sub-string quote[start:space_index] or substituting the values: quote[5:12] which will be the second word "stumble".
You should try to learn how to use a debugger of the IDE you are using, or try to print all intermediate values so you can see them.
The code basically prints each word separated by space line-by-line.
Commented Snippet:
# [ ] Print each word in the quote on a new line
quote = "they stumble who run fast"
start = 0 ## index of first character
space_index = quote.find(" ")
while space_index != -1: #the code in while needs to be explained to me
print(quote[start:space_index]) ## print characters from start index to space character
start = space_index +1 ## shift the start index to just after the up-coming space character
space_index = quote.find(" ", space_index +1) ## find the index of the next space character

Get only one word from line

How can I take only one word from a line in file and save it in some string variable?
For example my file has line "this, line, is, super" and I want to save only first word ("this") in variable word. I tried to read it character by character until I got on "," but I when I check it I got an error "Argument of type 'int' is not iterable". How can I make this?
line = file.readline() # reading "this, line, is, super"
if "," in len(line): # checking, if it contains ','
for i in line:
if "," not in line[i]: # while character is not ',' -> this is where I get error
word += line[i] # add it to my string
You can do it like this, using split():
line = file.readline()
if "," in line:
split_line = line.split(",")
first_word = split_line[0]
print(first_word)
split() will create a list where each element is, in your case, a word. Commas will not be included.
At a glance, you are on the right track but there are a few things wrong that you can decipher if you always consider what data type is being stored where. For instance, your conditional 'if "," in len(line)' doesn't make sense, because it translates to 'if "," in 21'. Secondly, you iterate over each character in line, but your value for i is not what you think. You want the index of the character at that point in your for loop, to check if "," is there, but line[i] is not something like line[0], as you would imagine, it is actually line['t']. It is easy to assume that i is always an integer or index in your string, but what you want is a range of integer values, equal to the length of the line, to iterate through, and to find the associated character at each index. I have reformatted your code to work the way you intended, returning word = "this", with these clarifications in mind. I hope you find this instructional (there are shorter ways and built-in methods to do this, but understanding indices is crucial in programming). Assuming line is the string "this, line, is, super":
if "," in line: # checking that the string, not the number 21, has a comma
for i in range(0, len(line)): # for each character in the range 0 -> 21
if line[i] != ",": # e.g. if line[0] does not equal comma
word += line[i] # add character to your string
else:
break # break out of loop when encounter first comma, thus storing only first word

remove the item in string

How do I remove the other stuff in the string and return a list that is made of other strings ? This is what I have written. Thanks in advance!!!
def get_poem_lines(poem):
r""" (str) -> list of str
Return the non-blank, non-empty lines of poem, with whitespace removed
from the beginning and end of each line.
>>> get_poem_lines('The first line leads off,\n\n\n'
... + 'With a gap before the next.\nThen the poem ends.\n')
['The first line leads off,', 'With a gap before the next.', 'Then the poem ends.']
"""
list=[]
for line in poem:
if line == '\n' and line == '+':
poem.remove(line)
s = poem.remove(line)
for a in s:
list.append(a)
return list
split and strip might be what you need:
s = 'The first line leads off,\n\n\n With a gap before the next.\nThen the poem ends.\n'
print([line.strip() for line in s.split("\n") if line])
['The first line leads off,', 'With a gap before the next.', 'Then the poem ends.']
Not sure where the + fits in as it is, if it is involved somehow either strip or str.replace it, also avoid using list as a variable name, it shadows the python list.
lastly strings have no remove method, you can .replace but since strings are immutable you will need to reassign the poem to the the return value of replace i.e poem = poem.replace("+","")
You can read all non-empty lines like this:
list_m = [line if line not in ["\n","\r\n"] for line in file];
Without looking at your input sample, I am assuming that you simply want your white spaces to be removed. In that case,
for x in range(0, len(list_m)):
list_m[x] = list_m[x].replace("[ ](?=\n)", "");

Patterns in Python

This is in python language.
I need to print this pattern, depending on the number of lines a user enters:
'##'
'# #'
The next pattern is three spaces away and so on...
This is my code but it prints the second number sign on a different line. I need them to go on the same line.
def drawPatternIII (lines):
for i in range(lines):
for j in range(1):
print('#')
for j in range(i+1):
print (' ', end = '')
print ('#')
please help!
You would need to add end="" to the first print() call. While you are at it, remove the pointless for loop with a single iteration.
A concise alternative would be
for i in range(lines):
print("#" + " "*i + "#")
The one liner version!
def drawPatternIII (lines):
list(map(print,["#" + " "*i + "#" for i in range(lines)]))

Resources