how not to replace certain characters in a string in python? - 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.

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

Is there a way to select a group of indexes and remove them?

I am making a decode method, which selects a set of index values within strings to remove. But right now the problem is i am unable to understand how to select a set of indices to remove
I have tried making a list of items to designate and remove if found in the string, but this would only work for only a few types of string sets.
def decode(string, n):
for i in range(0,len(string), n):
string = string.replace(string[i],'')
return string
here n is the number of values to remove at a given index as well as the index from where to start removing the said values
I understand how to step through an index, but I am not sure how to remove string values according to the index.
print(decode('#P#y#t#h#o#n#',1)) #this works out to be Python
print(decode('AxYLet1x3’s T74codaa7e!',3 )) #this does not, this is supposed to be 'Let's Code'
With "switcher" flag:
def decode(inp_str, n):
s = ''
flag = True
for i in range(0, len(inp_str), n):
flag = not flag
if flag: s += inp_str[i: i + n]
return s
print(decode('#P#y#t#h#o#n#', 1)) # Python
print(decode('AxYLet1x3’s T74codaa7e!', 3)) # Let’s code!
Different approach would be to pick the characters at the right positions:
def decode(string, n):
res = ''
for i in range(len(string)//(2*n)+1):
res += string[2*n*i+n:2*n*i+2*n]
return res
Don't change the size of an iterable when going through it!
The best would be to replace the character with some placeholder that can't be in the string, and then stripping it.
E.g. for your first example you already have that string format. Removing them outside the loop (remember, loop is for marking the characters for deletion) would be:
return ''.join(c for c in string if c!='#')
As for the loop itself in this approach, I'll leave it up to you to debug it now. ;) See how index moves in the loop, see what your replace in fact does! E.g. as I said in the comment, n=1 would go through literally every character, not every second character!
Another solution is smart slicing with indexes. Assuming from your examples that you want to 'remove n, keep n' code:
def decode(string, n):
result = ""
for i in range(n,len(string), 2*n): # first index we want to keep is n, next is 3n, 5n... so we're jumping by 2n each time
result += string[i: i+n]
return result
First, you're returning right after the first iteration. Second, you're only replacing character at n'th position with "".
This should do what you require, it'll replace every 'n' number of characters after every 'n' index:
def decode(string, n):
for i in range(0,len(string)-1,n):
string = string[:i] + string[i+n:] # Remove elements at index "i", till "i+n"
return string
Output:
print(decode('#P#y#t#h#o#n#',1)) # Output = Python
print(decode('AxYLet1x3’s T74codaa7e!',3 )) # Output = Let's Code

Converting uppercase to lowercase with hyphen

I'm processing some CSS code using Python, since they came from a JSON file (JSON doesn't accept hyphens) they have a particular notation eg.. font-size = fontSize, I'd like to convert every uppercases letter and put them back in the right CSS format inserting a hyphen right before the uppercase.
string = 'borderRadius: 0px, zIndex: 2, transform: translate(170px, 195px) skew(-30deg, 0deg), fontSize:30px'
def getIndices(string):
// get position of each capital letters.
index = [i for i, c in enumerate(string) if c.isupper()]
// code below would be inserted here.
// insert hyphen right before the upperscase
for i in index:
string = string[:i] + '-' + string[i:]
// once done, set string to lowercase since there are no uppercases in CSS properties
string = string.lower()
return string
getIndices(string)
The issue is that each time a hyphen is insered, the position of capital letters becomes off hence the insertion are off too.
I thought about enumarting the index and increasing each int in list by their index number, but I'm probably doing something not quite right.
...
index = [25, 35, 58]
for i, value in enumerate(index):
value = value + (i)
index[i] = value
Any suggestion would be helpful!
If I got it right, this is one way of doing it
for c in my_string:
print c
if c.isupper():
my_string = my_string.replace(c,"-%s" % c.lower())
print my_string # will print fontSize = font-size
You could simply do your insertions in reverse. Otherwise the first ones will change the offset of the last ones. This can be done by calling reversed on the index list before looping over it.
def getIndices(string):
# get position of each capital letters.
index = [i for i, c in enumerate(string) if c.isupper()]
# code below would be inserted here.
# insert hyphen right before the upperscase
for i in reversed(index):
string = string[:i] + '-' + string[i:]
# once done, set string to lowercase since there are no uppercases in CSS properties
string = string.lower()
return string
But it would be better to avoid:
string = string[:i] + '-' + string[i:]
As it makes four new strings every loop iteration.
By building a list and then calling '-'.join. The following works:
def getIndices(string):
# get position of each capital letters.
index = [i for i, c in enumerate(string) if c.isupper()]
# code below would be inserted here.
# insert hyphen right before the upperscase
l = []
e = len(string)
for i in reversed(index):
l.append(string[i:e])
e = i
l.append(string[:e])
l.reverse()
string = '-'.join(l)
# once done, set string to lowercase since there are no uppercases in CSS properties
string = string.lower()
return string
I'd like to do:
l = []
e = len(string)
for i, c in reversed(enumerate(string)):
if c.isupper():
l.append(string[i:e])
e = i
l.append(string[:e])
l.reverse()
string = '-'.join(l)
[The code above does not work as it results in TypeError: argument to reversed() must be a sequence but the error is misleading the argument must either be a sequence or an object that has __reversed__ defined]
But when they added reversed they didn't think about making it applicable to all built-in iterator functions by defining __reversed__ that returns the reverse they are iterating over an iterable that has a __reversed__. I've implemented an enumerate that works that way and find it Pythonic. Oddly it works on xrange but not on enumerate so the code becomes:
def getIndices(string):
l = []
e = len(string)
for i in reversed(xrange(len(string))):
if string[i].isupper():
l.append(string[i:e])
e = i
l.append(string[:e])
l.reverse()
string = '-'.join(l)
string = string.lower()
return string

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

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]))

List entries to variables: ttk python

I am trying to shift the letters of a string over by 1 each time a while loop runs(so "A" becomes "B", "B" becomes "C" and so on each time through).
I need to have each result displayed so I can compare them. What I don't want to do but know how to do is create 26 different functions each one shifting the letters one letter farther but this seems a bit ridiculous.
How do I assign a variable to ttk each time the while loop goes through?
I thought this would assign "ls" plus whatever the count was on (ls1, ls2, ls3...) to each variable but it does not. It throws an error every time.
def shift1(*args):
s = code.get()
storage = []
count = 1
while (count <= 26):
l = [ord(i) for i in s]
sh = ([chr(i + count) for i in l])
storage.append(sh)
("ls"+str(count)).set(storage(count - 1))
count += 1
It give me an error that says
AttributeError: 'str' object has no attribute 'set'
Like I said I could just use this function 26 times each time assigning a diff ttk variable.
def shift1(*args):
s = code.get()
l = [ord(i) for i in s]
sh1.set(''.join([chr(i + 1) for i in l]))
This will essentially bypass the loop, but I know there has to be a better way.
Very new to python and ttk so any help is appreciated.
You don't need to use a while loop, you can just iterate using a for loop instead. As with Bemmu's answer this forces the characters to be all upper case, as it makes it easier. But you can modified a little more so it checks based on upper or lower case characters.
def shift(str):
str =str.upper()
for i in range(26):
print "".join([chr((ord(x)-65+i)%26+65) for x in str])
shift("hello")
You can see this in operation here: http://codepad.org/OaBXM4s2
Here is a way to rotate the characters in a string around, assuming there are only A-Z letters in your string.
string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(10):
string = "".join([chr((ord(letter) - ord('A') + 1) % 26 + ord('A')) for letter in string])
print string
The idea is that each letter has an ASCII code difference from the letter A. So letter A would be 0, letter B is 1. When letter Z is shifted forward, it needs to go back to A. This is where the modulo (%) comes in, it shifts the letter Z back to A if needed.
Output:
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
GHIJKLMNOPQRSTUVWXYZABCDEF
HIJKLMNOPQRSTUVWXYZABCDEFG
IJKLMNOPQRSTUVWXYZABCDEFGH
JKLMNOPQRSTUVWXYZABCDEFGHI
KLMNOPQRSTUVWXYZABCDEFGHIJ

Categories

Resources