string .join method confusion - python

I tried to join a sample string in three ways, first entered by the code and then entered by user input. I got different results.
#Why isn't the output the same for these (in python 3.10.6):
sampleString = 'Fred','you need a nap! (your mother)'
ss1 = ' - '.join(sampleString)
print(ss1), print()
sampleString = input('please enter something: ') #entered 'Fred','you need a nap! (your mother)'
ss2 = ' - '.join(sampleString)
print(ss2)
sampleString = input(['Fred','you need a nap! (your mother)'])
ss2 = ' - '.join(sampleString)
print(ss2)
output:
Fred - you need a nap! (your mother)
please enter something: 'Fred','you need a nap! (your mother)'
' - F - r - e - d - ' - , - ' - y - o - u - - n - e - e - d - - a - - n - a - p - ! - - ( - y - o - u - r - - m - o - t - h - e - r - ) - '
['Fred', 'you need a nap! (your mother)']

When you do
sampleString = 'Fred','you need a nap! (your mother)'
Because of the comma, sampleString is a tuple containing two strings. When you join it, the delimiter is put between each element of the tuple. So it's put between the strings Fred and you need a nap! (your mother).
When you do
sampleString = input('please enter something: ')
sampleString is a string. When you join it, the delimiter is put between each element of the string. So it's put between each character.
You can see this difference if you do print(sampleString) in each case.

In the first case, sampleString = 'Fred','you need a nap! (your mother)' is a tuple consisting of two strings. When you join them the separator (-) is put between them.
In the second case sampleString is just a str, not a tuple. So the separate is placed between each element (character) of the string.

The first block of code is joining the elements of the tuple sampleString using the string ' - ' as a separator. In the second block of code, the user input is being treated as a single string, so the join() method is trying to join the characters of the string using the separator ' - '. This is why the output is different. If you want the second block of code to produce the same output as the first block, you should change the user input to be a tuple or a list of strings:
sampleString = ('Fred', 'you need a nap! (your mother)')

Related

how to I make the code to print the numbers given and and show what it equals

I tried to make just add print(a+b) and I only got what it equals I don't know what to do I can't find it or look for it online.
You are mixing up printing a string vs. printing an expression.
Printing a string like print('hello world') will print the literal message because you've indicated it's a string with quotes.
However, if you provide an expression like print(a+b), it will evaluate that expression (calculate the math) and then print the string representation of that evaluation.
Now, what you want is actually a mix of both, you want to print a string that has certain parts replaced with an expression. This can be done by "adding" strings and expressions together like so:
print(a + '+' + b + '=' + (a+b))
Notice the difference between + without quotes and '+' with quotes. The first is the addition operator, the second is the literal plus character. Let's break down how the print statement parses this. Let's say we have a = 5 and b = 3. First, we evaluate all the expressions:
print(5 + '+' + 3 + '=' + 8)
Now, we have to add a combination of numbers with strings. The + operator acts differently depending on context, but here it will simply convert everything into a string and then "add" them together like letters or words. Now it becomes something like:
print('5' + '+' + '3' + '=' + '8')
Notice how each number is now a string by the surrounding quotes. This parses to:
print('5+3=8')
which prints the literal 5+3=8
You mean like that:
a = int(input("Give me a number man: "))
b = int(input("Give me another number: "))
print(f'print({a} + {b}) = {a + b}')
print(f'print({a} - {b}) = {a - b}')
print(f'print({a} * {b}) = {a * b}')
print(f'print({a} // {b}) = {a // b}')
print("Look at all those maths!")
Output
Give me a number man: 3
Give me another number: 2
print(3 + 2) = 5
print(3 - 2) = 1
print(3 * 2) = 6
print(3 // 2) = 1
Look at all those maths!

Python separation by space

n = int(input("Give a number: "))
word = str(input("Give a word: "))
print(word.upper()*n)
n = 4
word = apple
output should be:
APPLE APPLE APPLE APPLE
now my problem is:
my output is APPLEAPPLEAPPLEAPPLE and I don't know how to put spaces between them.
I can't use split tho.
Thanks for the help.
Create a list of word.upper() and join its elements by separating them with a space:
lst = [word.upper()] * n
print(' '.join(lst))
print(' '.join([word]*n))
Expalanation:
[word] - a list of single word
[word]*n - a list of n elements, each element of list is word
Python string method join() returns a string in which the string elements of sequence have been joined by str separator.
https://www.tutorialspoint.com/python/string_join.htm
Just replace print(word.upper()*n) with print((word.upper() + " ")*n)

I want to output the python input as it is

i want this result.
---input---
"""
* name
- jon
* age
- 20
* hobby
- walk
"""
--- output ---
* name
- jon
* age
- 20
* hobby
- walk
----------------
I want to print as it is entered
Here is the code I wrote.
val = ""
vals = []
while True:
val = input()
if val == 'q':
break
else:
vals.append(val)
print(vals)
result
['* name', ' - jon', '* age', ' - 20', '* hobby', ' - walk']
help me!!!!
A number of ways to do this.
Print each item in a for loop.
for val in vals:
print(val)
Join the list items into a string, each item separated by newlines, then print that.
print("\n".join(vals))
Treat the items of the list as separate arguments to print() and use a newline as a separator.
print(*vals, sep="\n")
I like #3 because it`s short and it doesn't create a temporary string containing all the items like #2.

How do I add spaces between characters in an output statement when I am multiplying

For this program, the goal is to output a right triangle based on a user specified height triangle_height and symbol triangle_char. We are meant to create a triangle out of a user-inputted height and character, created by repeating a string to make a new string. So far I have:
triangle_char = input('Enter a character:\n')
triangle_height = int(input('Enter triangle height:\n'))
print('')
for x in range(1, triangle_height + 1):
print(x * triangle_char)
Which runs and outputs a tringle of the inputted height made of the inputted character however, the printed triangle is supposed to have spaces between every character
(ex: * not: *
* * **
* * * ***
How do I get spaces in between the printed characters?
You can just add a ' ' character after triangle_char like so:
for x in range(1, triangle_height + 1):
print(x * (triangle_char + ' '))
This does not produce trailing spaces at the ends of the lines.
Instead it uses the very pythonic way of joining lists
triangle_height = 5
triangle_char = "*"
for x in range(triangle_height):
print(" ".join(triangle_char * (x+1)))

How to change the following output into a proper string?

I'm trying to code a chatbot that will print a string containing n times the first letter of my name, followed by "n" and then followed by n-1 times the second letter in my name.
Example:
name: chris
n = 5 (since there are 5 letters in the name)
n-1 = 4
first letter of the name: c
second letter of the name: h
The string I want to generate: ccccc5hhhh
My problem: The string generated is in brackets which I don't want. I want the string to be exactly as "ccccc5hhhh", no spaces; all in one line, but I keep getting ['c','c','c','c','c']5['h','h','h','h'] as the output.
st1 = input("First name? ==> ")
print("Please enter the first letter of your name")
letter = input ("First letter? ==>? ")
if (letter == st1[0]):
# initializing list of lists
test_list = st1[0]
test_list1 = st1[1]
# repeat letters n times
res = [ele for ele in test_list for i in range(len(st1))]
res2 = [ele for ele in test_list1 for i in range(len(st1)-1)]
# printing result
print(str(res), len(st1), str(res2))
You are looking for the join function. Using , with your arguments will insert a space though.
To get the result you are looking for you will want:
print(''.join(res) + str(len(st1)) + ''.join(res2))
Instead of converting your lists into string you can use the .join() function, like so ''.join(res)
So you final line should be:
print(''.join(res) + str(len(st1)) + ''.join(res2))
You're overcomplicating this. Just use string multiplication.
s = 'chris'
n = len(s)
res1 = s[0] * n
res2 = s[1] * (n - 1)
print(res1 + str(n) + res2) # -> ccccc5hhhh

Categories