Related
So I have a list of numbers (answer_index) which correlate to the index locations (indicies) of a characters (char) in a word (word). I would like to use the numbers in the list as index inputs later (indexes) on in code to replace every character except my chosen character(char) with "*" so that the final print (new_word) in this instance would be (****ee) instead of (coffee). it is important that (word) maintains it's original value while (new_word) becomes the modified version. Does anyone have a solution for turning a list into valid index inputs? I will also except easier ways to meet my goal. (Note: I am extremely new to python so I'm sure my code looks horrendous) Code below:
word = 'coffee'
print(word)
def find(string, char):
for i, c in enumerate(string):
if c == char:
yield i
string = word
char = "e"
indices = (list(find(string, char)))
answer_index = (list(indices))
print(answer_index)
for t in range(0, len(answer_index)):
answer_index[t] = int(answer_index[t])
indexes = [(answer_index)]
new_character = '*'
result = ''
for i in indexes:
new_word = word[:i] + new_character + word[i+1:]
print(new_word)
You hardly ever need to work with indices directly:
string = "coffee"
char_to_reveal = "e"
censored_string = "".join(char if char == char_to_reveal else "*" for char in string)
print(censored_string)
Output:
****ee
If you're trying to implement a game of hangman, you might be better off using a dictionary which maps characters to other characters:
string = "coffee"
map_to = "*" * len(string)
mapping = str.maketrans(string, map_to)
translated_string = string.translate(mapping)
print(f"All letters are currently hidden: {translated_string}")
char_to_reveal = "e"
del mapping[ord(char_to_reveal)]
translated_string = string.translate(mapping)
print(f"'{char_to_reveal}' has been revealed: {translated_string}")
Output:
All letters are currently hidden: ******
'e' has been revealed: ****ee
The easiest and fastest way to replace all characters except some is to use regular expression substitution. In this case, it would look something like:
import re
re.sub('[^e]', '*', 'coffee') # returns '****ee'
Here, [^...] is a pattern for negative character match. '[^e]' will match (and then replace) anything except "e".
Other options include decomposing the string into an iterable of characters (#PaulM's answer) or working with bytearray instead
In Python, it's often not idiomatic to use indexes, unless you really want to do something with them. I'd avoid them for this problem and instead just iterate over the word, read each character and and create a new word:
word = "coffee"
char_to_keep = "e"
new_word = ""
for char in word:
if char == char_to_keep:
new_word += char_to_keep
else:
new_word += "*"
print(new_word)
# prints: ****ee
This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work:
for i in range(0,len(line)):
if (line[i]==";" and i in rightindexarray):
line[i]=":"
It gives the error
line[i]=":"
TypeError: 'str' object does not support item assignment
How can I work around this to replace the semicolons by colons? Using replace does not work as that function takes no index- there might be some semicolons I do not want to replace.
Example
In the string I might have any number of semicolons, eg "Hei der! ; Hello there ;!;"
I know which ones I want to replace (I have their index in the string). Using replace does not work as I'm not able to use an index with it.
Strings in python are immutable, so you cannot treat them as a list and assign to indices.
Use .replace() instead:
line = line.replace(';', ':')
If you need to replace only certain semicolons, you'll need to be more specific. You could use slicing to isolate the section of the string to replace in:
line = line[:10].replace(';', ':') + line[10:]
That'll replace all semi-colons in the first 10 characters of the string.
You can do the below, to replace any char with a respective char at a given index, if you wish not to use .replace()
word = 'python'
index = 4
char = 'i'
word = word[:index] + char + word[index + 1:]
print word
o/p: pythin
Turn the string into a list; then you can change the characters individually. Then you can put it back together with .join:
s = 'a;b;c;d'
slist = list(s)
for i, c in enumerate(slist):
if slist[i] == ';' and 0 <= i <= 3: # only replaces semicolons in the first part of the text
slist[i] = ':'
s = ''.join(slist)
print s # prints a:b:c;d
If you want to replace a single semicolon:
for i in range(0,len(line)):
if (line[i]==";"):
line = line[:i] + ":" + line[i+1:]
Havent tested it though.
You cannot simply assign value to a character in the string.
Use this method to replace value of a particular character:
name = "India"
result=name .replace("d",'*')
Output: In*ia
Also, if you want to replace say * for all the occurrences of the first character except the first character,
eg. string = babble output = ba**le
Code:
name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
back=fromSecondCharacter.replace(front,'*')
return front+back
This should cover a slightly more general case, but you should be able to customize it for your purpose
def selectiveReplace(myStr):
answer = []
for index,char in enumerate(myStr):
if char == ';':
if index%2 == 1: # replace ';' in even indices with ":"
answer.append(":")
else:
answer.append("!") # replace ';' in odd indices with "!"
else:
answer.append(char)
return ''.join(answer)
to use the .replace() method effectively on string without creating a separate list
for example take a look at the list username containing string with some white space, we want to replace the white space with an underscore in each of the username string.
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
to replace the white spaces in each username consider using the range function in python.
for name in names:
usernames.append(name.lower().replace(' ', '_'))
print(usernames)
Or if you want to use one list:
for user in range(len(names)):
names[user] = names[user].lower().replace(' ', '_')
print(names)
How about this:
sentence = 'After 1500 years of that thinking surpressed'
sentence = sentence.lower()
def removeLetter(text,char):
result = ''
for c in text:
if c != char:
result += c
return text.replace(char,'*')
text = removeLetter(sentence,'a')
If you are replacing by an index value specified in variable 'n', then try the below:
def missing_char(str, n):
str=str.replace(str[n],":")
return str
To replace a character at a specific index, the function is as follows:
def replace_char(s , n , c):
n-=1
s = s[0:n] + s[n:n+1].replace(s[n] , c) + s[n+1:]
return s
where s is a string, n is index and c is a character.
I wrote this method to replace characters or replace strings at a specific instance. instances start at 0 (this can easily be changed to 1 if you change the optional inst argument to 1, and test_instance variable to 1.
def replace_instance(some_word, str_to_replace, new_str='', inst=0):
return_word = ''
char_index, test_instance = 0, 0
while char_index < len(some_word):
test_str = some_word[char_index: char_index + len(str_to_replace)]
if test_str == str_to_replace:
if test_instance == inst:
return_word = some_word[:char_index] + new_str + some_word[char_index + len(str_to_replace):]
break
else:
test_instance += 1
char_index += 1
return return_word
You can do this:
string = "this; is a; sample; ; python code;!;" #your desire string
result = ""
for i in range(len(string)):
s = string[i]
if (s == ";" and i in [4, 18, 20]): #insert your desire list
s = ":"
result = result + s
print(result)
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
for i in names:
if " " in i:
i = i.replace(" ", "_")
print(i)
Output:
Joey_Tribbiani
Monica_Geller
Chandler_Bing
Phoebe_Buffay
My problem was that I had a list of numbers, and I only want to replace a part of that number, soy I do this:
original_list = ['08113', '09106', '19066', '17056', '17063', '17053']
# With this part I achieve my goal
cves_mod = []
for i in range(0,len(res_list)):
cves_mod.append(res_list[i].replace(res_list[i][2:], '999'))
cves_mod
# Result
cves_mod
['08999', '09999', '19999', '17999', '17999', '17999']
Even more simpler:
input = "a:b:c:d"
output =''
for c in input:
if c==':':
output +='/'
else:
output+=c
print(output)
output: a/b/c/d
i tried using this instead as a 2 in 1
usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
# write your for loop here
for user in range(0,len(usernames)):
usernames[user] = usernames[user].lower().replace(' ', '_')
print(usernames)
Cleaner way to replace character at a specific index
def replace_char(str , index , c):
return str[:index]+c+str[index+1:]
def onlyLetters(s):
for i in range(len(s)):
if s[i] == " ":
s = s[:i] + s[i+1:]
return s
return s
Why is my above loop not working? It seems like it's only doing it once.
For example, if i have the string "Hello how are you", it's returning "Hellohow are you". I want it to check the string again and remove another space, and keep doing it until there are no spaces left. How do I fix this code?
Your code is stopping after the first space is replaced because you've told it to. You have return s inside the loop, and when that is reached, the rest of the loop is abandoned since the function exits. You should remove that line entirely.
There's another issue though, related to how you're indexing. When you iterate on range(len(s)) for your indexes, you're going to go to the length of the original string. If you've removed some spaces, however, those last few indexes will no longer be valid (since the modified string is shorter). Another similar issue will come up if there are two spaces in a row (as in "foo bar"). Your code will only be able to replace the first one. After the first space is removed, the second spaces will move up and be at the same index, but the loop will move on to the next index without seeing it.
You can fix this in two different ways. The easiest fix is to loop over the indexes in reverse order. Removing a space towards the end won't change the indexes of the earlier spaces, and the numerically smallest indexes will always be valid even as the string shrinks.
def onlyLetters(s):
for i in range(len(s)-1, -1, -1): # loop in reverse order
if s[i] == " ":
s = s[:i] + s[i+1:]
return s
The other approach is to abandon the for loop for the indexes and use a while loop while manually updating the index variable:
def onlyLetters(s):
i = 0
while i < len(s):
if s[i] == " ":
s = s[:i] + s[i+1:]
else:
i += 1
return s
If you want to remove all spaces, use str.replace():
sentence = ' Freeman was here'
sentence.replace(" ", "")
>>> 'Freemanwashere'
If you want to remove leading and ending spaces, use str.strip():
sentence = ' Freeman was here'
sentence.strip()
>>> 'Freeman was here'
If you want to remove duplicated spaces, use str.split():
sentence = ' Freeman was here'
" ".join(sentence.split())
>>> 'Freemanwashere'
If you also want to remove all the other strange whitespace characters that exist in unicode you can use re.sub with the re.UNICODE arguement:
text = re.sub(r"\s+", "", text, flags=re.UNICODE)
or something like this,it's handles any whitespace characters that you're not thinking of 😉 :
>>> import re
>>> re.sub(r'\s+', '', 'Freeman was here')
'Freemanwashere'
if you don’t want to use anything like replace() or join() etc. you can do this :
def filter(input):
for i in input:
yield " " if i in " ,.?!;:" else i
def expand(input):
for i in input:
yield None if i == " " else object(), i
def uniq(input):
last = object()
for key, i in input:
if key == last:
continue
yield key, i
def compact(input):
for key, i in input:
yield i
yourText = compact(uniq(expand(filter(input()))))
just use python replace() method for Strings.
s.replace(" ","")
It's a little hard to tell, because the indentation in your example is hard to understand. But it looks to me like after you encounter and remove the very first space, you are returning s. So you only get a chance to remove one space before returning.
Try only returning s once you are out of the for loop.
You can do s.replace(" ", ""). This will take all your spaces (" ") and replace it by nothing (""), effectively removing the spaces.
You're returning the function after the first occurrence of a ",", which means it exits the loop and the function altogether. That's why it's only working for the first comma.
Try this,
def onlyLetters(s):
length=len(s)
i=0
while(i<length):
if s[i] == " ":
s = s[:i] + s[i+1:]
length=len(s)
else
i+=1
return s
If you want to use your own code only then try running this:
def onlyLetters(s):
for i in range(len(s)):
if s[i] == " ":
s = s[:i] + s[i+1:]
return s
or better you may use:
def onlyLetters(s):
return s.replace(" ","")
def remove_spaces(text):
text_with_out_spaces='';
while text!='':
next_character=text[0];
if next_character!=' ':
text_with_out_spaces=text_with_out_spaces +next_character;
text=text[1:];
return text_with_out_spaces
print remove_spaces("Hi Azzam !! ?");
So I want to change the last character in a string to lower case. The code below is the method I am using to print a string backwards, but list leaves the last character as a capital and I can't figure out how to fix this!
if s[-1] == "x":
new = ""
last_index = len(s)-1
for i in range(last_index, -1, -1):
new += s[i]
s = new
s = "".join(word[0].upper() + word[1:] for word in s.split())
print (s)
e.g:
The input is:
Inbox
and this outputs:
XobnI
But I want it to output:
Xobni
Thanks in advance!
Use str.title:
>>> "Inbox"[::-1].title()
'Xobni'
This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work:
for i in range(0,len(line)):
if (line[i]==";" and i in rightindexarray):
line[i]=":"
It gives the error
line[i]=":"
TypeError: 'str' object does not support item assignment
How can I work around this to replace the semicolons by colons? Using replace does not work as that function takes no index- there might be some semicolons I do not want to replace.
Example
In the string I might have any number of semicolons, eg "Hei der! ; Hello there ;!;"
I know which ones I want to replace (I have their index in the string). Using replace does not work as I'm not able to use an index with it.
Strings in python are immutable, so you cannot treat them as a list and assign to indices.
Use .replace() instead:
line = line.replace(';', ':')
If you need to replace only certain semicolons, you'll need to be more specific. You could use slicing to isolate the section of the string to replace in:
line = line[:10].replace(';', ':') + line[10:]
That'll replace all semi-colons in the first 10 characters of the string.
You can do the below, to replace any char with a respective char at a given index, if you wish not to use .replace()
word = 'python'
index = 4
char = 'i'
word = word[:index] + char + word[index + 1:]
print word
o/p: pythin
Turn the string into a list; then you can change the characters individually. Then you can put it back together with .join:
s = 'a;b;c;d'
slist = list(s)
for i, c in enumerate(slist):
if slist[i] == ';' and 0 <= i <= 3: # only replaces semicolons in the first part of the text
slist[i] = ':'
s = ''.join(slist)
print s # prints a:b:c;d
If you want to replace a single semicolon:
for i in range(0,len(line)):
if (line[i]==";"):
line = line[:i] + ":" + line[i+1:]
Havent tested it though.
You cannot simply assign value to a character in the string.
Use this method to replace value of a particular character:
name = "India"
result=name .replace("d",'*')
Output: In*ia
Also, if you want to replace say * for all the occurrences of the first character except the first character,
eg. string = babble output = ba**le
Code:
name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
back=fromSecondCharacter.replace(front,'*')
return front+back
This should cover a slightly more general case, but you should be able to customize it for your purpose
def selectiveReplace(myStr):
answer = []
for index,char in enumerate(myStr):
if char == ';':
if index%2 == 1: # replace ';' in even indices with ":"
answer.append(":")
else:
answer.append("!") # replace ';' in odd indices with "!"
else:
answer.append(char)
return ''.join(answer)
to use the .replace() method effectively on string without creating a separate list
for example take a look at the list username containing string with some white space, we want to replace the white space with an underscore in each of the username string.
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
to replace the white spaces in each username consider using the range function in python.
for name in names:
usernames.append(name.lower().replace(' ', '_'))
print(usernames)
Or if you want to use one list:
for user in range(len(names)):
names[user] = names[user].lower().replace(' ', '_')
print(names)
How about this:
sentence = 'After 1500 years of that thinking surpressed'
sentence = sentence.lower()
def removeLetter(text,char):
result = ''
for c in text:
if c != char:
result += c
return text.replace(char,'*')
text = removeLetter(sentence,'a')
If you are replacing by an index value specified in variable 'n', then try the below:
def missing_char(str, n):
str=str.replace(str[n],":")
return str
To replace a character at a specific index, the function is as follows:
def replace_char(s , n , c):
n-=1
s = s[0:n] + s[n:n+1].replace(s[n] , c) + s[n+1:]
return s
where s is a string, n is index and c is a character.
I wrote this method to replace characters or replace strings at a specific instance. instances start at 0 (this can easily be changed to 1 if you change the optional inst argument to 1, and test_instance variable to 1.
def replace_instance(some_word, str_to_replace, new_str='', inst=0):
return_word = ''
char_index, test_instance = 0, 0
while char_index < len(some_word):
test_str = some_word[char_index: char_index + len(str_to_replace)]
if test_str == str_to_replace:
if test_instance == inst:
return_word = some_word[:char_index] + new_str + some_word[char_index + len(str_to_replace):]
break
else:
test_instance += 1
char_index += 1
return return_word
You can do this:
string = "this; is a; sample; ; python code;!;" #your desire string
result = ""
for i in range(len(string)):
s = string[i]
if (s == ";" and i in [4, 18, 20]): #insert your desire list
s = ":"
result = result + s
print(result)
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
for i in names:
if " " in i:
i = i.replace(" ", "_")
print(i)
Output:
Joey_Tribbiani
Monica_Geller
Chandler_Bing
Phoebe_Buffay
My problem was that I had a list of numbers, and I only want to replace a part of that number, soy I do this:
original_list = ['08113', '09106', '19066', '17056', '17063', '17053']
# With this part I achieve my goal
cves_mod = []
for i in range(0,len(res_list)):
cves_mod.append(res_list[i].replace(res_list[i][2:], '999'))
cves_mod
# Result
cves_mod
['08999', '09999', '19999', '17999', '17999', '17999']
Even more simpler:
input = "a:b:c:d"
output =''
for c in input:
if c==':':
output +='/'
else:
output+=c
print(output)
output: a/b/c/d
i tried using this instead as a 2 in 1
usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
# write your for loop here
for user in range(0,len(usernames)):
usernames[user] = usernames[user].lower().replace(' ', '_')
print(usernames)
Cleaner way to replace character at a specific index
def replace_char(str , index , c):
return str[:index]+c+str[index+1:]