How do I get rid of brackets? - python

def name(reading):
return reading
print(name([[10,9,9,10],2]))
When I get the program it prints [[10,9,9,10],2] but I need it to print without the extra brackets ending up with [10,9,9,10],2. I tried using things like (*reading, sep = ", ") but that only works when I use print directly. I ultimately want to know how to make reading = [10,9,9,10],2 and not [[10,9,9,10],2]. Thank you.

You can return it as a string using join()
def name(reading):
return ",".join(str(x) for x in reading)

reading=[[10,9,9,10],2]
def name(reading):
solution=""
reading = [[10,9,9,10],2]
for i in range(len(reading)):
solution+=str(reading[i])
if i<len(reading)-1:
solution+=","
return solution
print(name(reading))
How About this?
+and you should define reading in global scope.

You can use this:
def name(reading03=[[10,9,9,10],2]):
reading02 = str(reading03)
reading01 = reading02.replace("[", "")
reading = reading01.replace("]", "")
return reading
print(name)

Related

How to add input in the middle of a string?

I'm very new to programming, only started learning python ~4 days ago and I'm having trouble figuring out how to print a user input as a string, in between other strings on the same line. Being so new to programming, I feel like the answer is staring me right in the face but I don't have the tools or the knowledge to figure it out lol.
what I'm trying to do is:
Wow (PlayerName) that's cool
so far what I have is:
name = input("Name? ")
print("Wow") (print(name)) (print("that's cool"))
python came back with an error saying object 'NoneType' is not callable, so instead i tried to write it as a function and call that instead:
name = input("Name? ")
def name_call():
print(name)
print("Wow") (name_call()) (print("that's cool"))
same issue, I tried various similar things, but at this point I'm just throwing darts
I'm not 100% sure why neither of these worked, but I do know that it probably has something to do with me writing it incorrectly. I could just print the name on a new line, but I want to try and put them all on the same line if possible.
you can try this code:
# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using split() + slicing + join()
# initializing string
test_str = 'Wow that\'s cool!'
# printing original string
print("The original string is : " + str(test_str))
# initializing mid string
mid_str = (input('Please input name = '))
# splitting string to list
temp = test_str.split()
mid_pos = len(temp) // 3
# joining and construction using single line
res = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:])
# printing result
print("Formulated String : " + str(res))
The result will be like this:
The original string is : Wow that's cool!
Please input name = Alice
Formulated String : Wow Alice that's cool!
you can input any name to the program.
As others have said, I think you're looking for string interpolation. As of Python 3.6 we have f-strings.
name = input("Name? ")
print(f"Wow {name} that's cool")
https://www.programiz.com/python-programming/string-interpolation
Your print's need to be on new lines.
name = input("Name? ")
print("Wow")
print(name)
print("that's cool")
Python thinks you are trying to call the result of the print function (which returns None) as a function of its own.
|
V you are accidentally calling the return value here
print("Wow")(print(name))
val = 'name'
print(f"Wow {val} that's cool.")
Btw, if you want name_call() to play a role, the following code also works
def name_call():
return ('name')
print(f"Wow {name_call()} that's cool.")
You may use the format method to insert name into the string's placeholder {}:
print("Wow {} that's cool".format(str(name)))
x = str(input('Name: '))
print('user entered {} as their name'.format(x))

Python function help, does someone can tell me why it doesent work?

my task is to write a python program removes all characters or strings from a string (text)
specified in a list (strings_list). I got it like this but this doesen't work. Anybody can tell me what i got wrong or did I use a wrong function?
Thanks!!
def remove_strings(text, strings_list):
for strings_list in remove_strings:
strings_list.remove()
text_cleaned = remove_strings("yes, no, maybe..",
["yes", ","])
return text_cleaned
print(text_cleaned)
def removechar(text, strings_list):
newstrings = []
for i in strings_list:
if text in i:
newtext = ""
newtext = i
newtext = newtext.replace(text, "")
newstrings.append(newtext)
else:
newstrings.append(i)
print(newstrings)
return(newstrings)
also, .remove() isnt a function, you would have to use .replace(text, "") instead

How to do nothing while using replace() string method?

I am working with some strings and I am removing some characters from them by using replace(), for example:
a = 'monsterr'
new_a = a.replace("rr", "r")
new_a
However, let's say that now I receive the following string:
In:
a = 'difference'
new_a = a.replace("rr", "r")
new_a
Out:
'difference'
How can I return nothing if my string doesnt contain rr? Is there anyway of just pass or return nothing? I tried to:
def check(a_str):
if 'rr' in a_str:
a_str = a_str.replace("rr", "r")
return a_str
else:
pass
However, it doesn't work. The expected output would be for monsterwould be nothing.
Use return:
def check(a_str):
if 'rr' in a_str:
a_str = a_str.replace("rr", "r")
return a_str
For list comprehension:
a = ["difference", "hinderr"]
x = [i.replace("rr", "r") for i in a]
Just as a little easter egg, I figured I'd include this little gem as an option as well, if only because of your question:
How can I return nothing if my string doesnt contain rr? Is there anyway of just pass or return nothing?
Using boolean operators, you could take the if line completely out of check().
def check(text, dont_want='rr', want='r'):
replacement = text.replace(dont_want, want)
return replacement != text and replacement or None
#checks if there was a change after replacing,
#if True: returns replacement
#if False: returns None
test = "differrence"
check(test)
#difference
test = "difference"
check(test)
#None
Consider this un-pythonic or not, it's another option. Plus it's along the lines of his question.
"return none if string doesn't contain rr"
For those that don't know how or why this works, (and/or enjoy learning cool python tricks but don't know this) then here's the docs page explaining boolean operators.
P.S.
Technically speaking, it is un-pythonic due to it being a ternary operation. This does go against the "Zen of Python" ~ import this but coming from C style languages I enjoy them.

How to add space before a particular string in python

I have the following output after removing all spaces from a string
テレビを付けて
テレビつけて
つけて
テレビをオンにして
However, I'm trying to add a space either after the を character, or before つけて after テレビ
The desired output is as follows
テレビを 付けて
テレビ つけて
つけて
テレビを オンにして
I've tried to use some def function but not sure how to finish it off, or even if it'll work.
def teform(txt):
if x = "オンにして":
return " して"
elif y = "つけて":
return " つけて"
elif z = "付けて":
return " 付けて"
else:
return # ...(not sure what goes here)
You cannot use = to compare items, you must use ==.
Apart from the wrong comparing syntax, it seems you don't really know how to approach this – you don't need a loop of any kind. Just use txt.replace to target and change those specific substrings:
def teform(txt):
# add a space after を
txt = txt.replace ('を','を ')
# add a space between テレビ and つけて
txt = txt.replace ('テレビつけて', 'テレビ つけて')
return txt

How to concatenate two functions on the same line?

def headName():
print (Name[0].upper())
def tailName():
print (Name[1:].lower())
Name = input("Please enter a name ")
headName()
tailName()
That's my code; I want to know how to concatinate headName() and tailName(), so that they're on the same line. Thanks
You can't do that without rewriting the functions. The newline is added by print. Since you call print inside the functions, nothing you do outside the function can undo the newline that was already added inside.
A better idea is to have your functions return the values, and then do the printing outside:
def headName():
return Name[0].upper()
def tailName():
return Name[1:].lower()
Name = input("Please enter a name ")
print(headName(), tailName(), sep="")
Incidentally, what you are doing can also be accomplished directly with Name.title().
To print on the same line call them in one print statement, something like:
print(headName(), ' ', tailName())
You can also use string formatting, which in case that you wanted to customize further the output would give you more control over the outcome:
def headName():
return Name[0].upper()
def tailName():
return Name[1:].lower()
Name = input("Please enter a name ")
print('{}{}'.format(headName(), tailName()))
You can also try:
def headName():
print ((Name[0].upper()), end="")
This will cause your print function to end with nothing, instead of ending with a newline (default).
For more information: https://docs.python.org/3/whatsnew/3.0.html

Categories

Resources