How to remove brackets from output (i.e. [ ]) and other - python

I am having trouble getting the right output out for my code(for school). st = input string ch = input character(this is for python to search for ch in st) The code find the both uppercase and the lowercase of the character that I put in for ch, and shows their position in the output(in reverse order). So, I typed this code in
def whichPositionsRev (st, ch):
if ch in st:
inverseFindChar = [index for index,char in enumerate(list(st)) if char==ch ]
return "Yes..." + str(inverseFindChar[::-1])
else:
return "No"
I am suppose to get 'Yes...8 5 2 ' as a return value(if I typed in 'abXabXabX' for st and 'X' for ch), but I'm keep getting 'Yes...[8, 5, 2]' as an output. I want to know
which part code is causing it to put in brackets and commas in the return output?

Because you're calling str() on an array, you are getting the string representation of the array.
Replace
str(inverseFindChar[::-1])
with
" ".join(str(x) for x in inverseFindChar[::-1])

The part you're asking about is the str() function call. Python puts brackets and commas in the output for you to make it easier to see the array elements.
If you want to get the array elements separated by spaces, use
" ".join(map(str, inverseFindChar[::-1]))

Related

how can i use multiple returned indices in a for loop to update a variable?

My question is: is there any way i can somehow use all the returned capital letter indices and replace them ALL with an underscore? I wished to take the returned values from the uppercase_finder function and insert an underscore in front of those capitalized letters. However, when I run the program, I only get the first capital letter of input with an underscore. Can I somehow iterate all the returned uppercase indices into the part where I insert underscores?
def main():
first_input = input("input here: ")
uppercase_indice = uppercase_finder(first_input)
new_case = first_input[:uppercase_indice] + "_" + first_input[uppercase_indice:]
new_case = new_case.lower()
print(new_case)
def uppercase_finder(x):
for i in range(len(x)):
if x[i].isupper():
return i
main()
Okay so based on the assumption that the overall goal is to print out the string inputted all lowercase and an underscore appended to each letter that was uppercase.
You could iterate through each letter in the string without focusing on the indices at all. Something like:
def main():
first_input = input("input here: ")
updated_input = ""
for letter in first_input:
if(letter.isupper()):
updated_input += "_" + letter.lower()
else:
updated_input += letter
print(updated_input)
Output:
input here: HeLLo
_he_l_lo
Generally though if you want to stick with the uppercase_finder function, the return statement in the loop stops the loop the moment any letter that is uppercase is found. In order to get all of the indices of each letter that is uppercase you would need something like this:
def uppercase_finder(x):
list_of_indices = []
for i in range(len(x)):
if x[i].isupper():
list_of_indices.append(i)
return list_of_indices
Then in the main function you can iterate across the list:
for index in uppercase_indice:
# Make string manipulations for each index
It's obviously an assignment problem so I'm not going to spoon-feed the answer. But I can point out what's the problem in your uppercase_finder.
The problem is that it is returning the index as soon as it find the first upper case. What you can do is
def uppercase_finder(x):
uppercase_indices = []
for i in range(len(x)):
if x[i].isupper():
# Append the index to the list uppercase_indices
return uppercase_indices
There's some problem with your uppercase_finder function, 'return' denotes the end of a function, whenever a return is met, the function will immediately stop and exit with an returned value. For ur case, it seems u wanna return all the indices where there are a capital letter, u may use yield instead of return thus making the function a generator.
def uppercase_finder(x):
for i in range(len(x)):
if x[i].isupper():
yield i
use the output of a generator via a loop:
for capital_pos in uppercase_finder(first_input):
do_sth

Why the output is two string when I pass a one character string to a python function

I've created a function called swap for an experiment. The function is as below:
def swap(x):
return x[-1:] + x[1:-1] + x[0:1]
When I try to pass a string "a", the output is "aa". I am not sure how's that happen. Thanks in advance if someone knows the reason.
Your function returns a new string based on:
The last letter of your string (a)
everything after the first letter but before the last letter (empty in your case)
and the first letter of your string (a)
So because your last letter is your first letter, you get them twice.
To swap them correctly, you'll have to test for string length:
def swap(x):
if len(x) < 2:
return x
return x[-1] + x[1:-1] + x[0]
Now that you know that in the last line x is at least two characters long, you also don't need slicing for the first/last character and can use direct element access (x[0]/x[-1]).
Actually this is ok.
x[-1:] will return the last character, becuase -1 starts from the end
x[0:1] will return the first character from beginning
x[1:-1] is nothing in this case because you don't have the second character
Btw for swap use return x.reverse() or return x[::-1]

how not to replace certain characters in a string in python?

Let's say replace characters but not last "4" with "!" in a random string.
or replace characters but not middle "3" with "#" in a random string.
example 1:
input(hdasd1234)
output(!!!!!1234)
example 2:
input(asadfe455)
output(###dfe###)
x = str(input())
y = "!" * (len(x) - 4) + x[-4:]
print(x)
This code is not working.
For a very basic, direct solution, you can do this:
Example one:
string = input() #input automatically returns a string, so there's no need for str()
y = '!' * (len(string)-5) + string[4:]print (y) #remember to print y, not string because y is the modified version of your string
And example two
string = input()
y = "#" * 3 + string[3:6] + "#" * 3
print (y)
For a more flexible method to this approach, you should create a function. Assuming you are given the positions of where to change the string in a list, the string, and the specific marker to replace string[n] with, this should be fairly simple:
def replace_chars(string, positions, s):
new_string = []
for i in range(len(string)):
if i not in positions: #Checking if position, i, is not one of the marked positions
new_string.append(string[i])
else: #If it is a marked positions, append it with the marker, s, or more specifically '#'
new_string.append(s)
return ''.join(new_string) #Make the list a string
This could be written in a 1-2 lines long function with one line for loops but this formatting is better for readability. But if you were to do it in 1-2 lines, it would look like this:
def replace_chars(string, positions, s):
new_string = [string[i] if i not in positions else s for i in range(len(string))]
return ''.join(new_string)
The code is printing the value of x which is not modified.
Your code logic is creating a new variable y with the result and the x is unmodified.
However,you are printing the value of x which is the exact same input.
The logic seems to be working and the result is correct for the value of y.
Please check on that.
If any issues,please post the error log or the results.

How does the loop help iterate in this code

The problem at hand is that given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.
Desired result is a list of all possible strings we could create.
Eg:
Input:
S = "a1b2"
Output:
["a1b2", "a1B2", "A1b2", "A1B2"]
I see the below code generates the correct result, but I'm a beginner in Python and can you help me understand how does loop line 5 & 7 work, which assign value to res.
def letterCasePermutation(self, S):
res = ['']
for ch in S:
if ch.isalpha():
res = [i+j for i in res for j in [ch.upper(), ch.lower()]]
else:
res = [i+ch for i in res]
return res
The result is a list of all possible strings up to this point. One call to the function handles the next character.
If the character is a non-letter (line 7), the comprehension simply adds that character to each string in the list.
If the character is a letter, then the new list contains two strings for each one in the input: one with the upper-case version added, one for the lower-case version.
If you're still confused, then I strongly recommend that you make an attempt to understand this with standard debugging techniques. Insert a couple of useful print statements to display the values that confuse you.
def letterCasePermutation(self, S):
res = ['']
for ch in S:
print("char = ", ch)
if ch.isalpha():
res = [i+j for i in res for j in [ch.upper(), ch.lower()]]
else:
res = [i+ch for i in res]
print(res)
return res
letterCasePermutation(None, "a1b2")
Output:
char = a
['A', 'a']
char = 1
['A1', 'a1']
char = b
['A1B', 'A1b', 'a1B', 'a1b']
char = 2
['A1B2', 'A1b2', 'a1B2', 'a1b2']
Best way to analyze this code is include the line:
print(res)
at the end of the outer for loop, as first answer suggests.
Then run it with the string '123' and the string 'abc' which will isolate the two conditionals. This gives the following output:
['1']
['12']
['123']
and
['A','a']
['AB','Ab','aB','ab']
['ABC','ABc','AbC','aBC','Abc','aBc','abC','abc']
Here we can see the loop is just taking the previously generated list as its input, and if the next string char is not a letter, is simply tagging the number/symbol onto the end of each string in the list, via string concatenation. If the next char in the initial input string is a letter, however, then the list is doubled in length by creating two copies for each item in the list, while simultaneously appending an upper version of the new char to the first copy, and a lower version of the new char to the second copy.
For an interesting result, see how the code fails if this change is made at line 2:
res = []

ValueError: invalid literal for int() with base 10: 'Blusson Hall'

This is homework but I'm not looking for a handout. Error messages haven't really been explained yet so I don't know how to fix this or why it's happening. I know it happens when I try to make s into an integer but I get a different error if I don't so I'm a little lost...
I've also tried looking at some of the other posts with similar problems but I'm very new to Python and I can't follow the explanations.
It's a pretty straightforward function, I think.
I've tried converting it to an integer to I can perform the range function on it but that doesn't seem to be working. The program is supposed to first put a space between the letters in "Blusson Hall" and add an additional space if there is already one there and finally print that design around the final product. Thanks for any help.
def spaced(s):
n = int (s)
for [i] in range (n):
if [i] != " ":
n == n+ [i] + " "
if [i] == " ":
n == n+ [i] + " "
print "-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-"
print ". ."
print "- " + str (n)+ " -"
print ". ."
print "-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-"
#- you write (5 marks) -#
###################
#- Tester's code -#
###################
spaced("Blusson Hall")
Your problem is that you are calling spaced with a non-numeric string and then trying to convert that to an integer:
>>> int("Blusson Hall")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Blusson Hall'
If you want a range based on the length of the string, you can use something like:
for i in range(len(s)):
as in:
>>> s = "Busson Hall"
>>> for i in range(len(s)):
... print i
...
0
1
2
3
4
5
6
7
8
9
10
And, as some extra assistance, you would use s[i] to get the i'th (zero being the first one, of course) character of s. In addition, you probably want to start with an empty string and then append individual characters to it (from the original string and whatever spaces you want added) to gradually build it up before returning it.
For example, this snippet duplicates every character with a colon between them:
>>> s = "paxdiablo"
>>> s2 = ""
>>> for i in range(len(s)):
... s2 = "%s%s:%s:" % (s2, s[i], s[i])
...
>>> print s2
p:p:a:a:x:x:d:d:i:i:a:a:b:b:l:l:o:o:
Short of writing the code for you (which, intelligently, you decided against asking for), that's probably all the help I can give (though feel free to ask any questions you want and I'll offer further advice).
i think i see the issue.
instead of
n = int(s)
try
n = len(s)
You can't convert a string to an integer, and that's what you try to do when you type:
n = int(s)
spaced only takes one argument, 's', and you pass in a string, then try to convert it to an integer. I think what you want is probably
n = len(s)
But really, you don't even need that. Since strings are iterable, you can just loop over it like:
for ch in s:
...do stuff here...
And if the index within s for each char is helpful/easier, enumerate() will do that for you:
for idx, ch in enumerate(s):
...do stuff here...
Just so you know, you don't actually need a for loop at all. Since strings are iterable and 'join()' takes an iterable as an argument, you can replace almost all of your code with this:
' '.join(s)
That looks odd if you haven't done much with Python before. I've created a string ' ', and join() is a method that all strings have available. Join takes some iterable object (like a list, or even another string) and puts the string that is the object of the join between each element of the iterable. So, in this case, it puts ' ' between each element of the string 's'.

Categories

Resources