Python best way to remove char from string by index [duplicate] - python

This question already has answers here:
Remove char at specific index - python
(8 answers)
Closed 2 months ago.
I'm removing an char from string like this:
S = "abcd"
Index=1 #index of string to remove
ListS = list(S)
ListS.pop(Index)
S = "".join(ListS)
print S
#"acd"
I'm sure that this is not the best way to do it.
EDIT
I didn't mentioned that I need to manipulate a string size with length ~ 10^7.
So it's important to care about efficiency.
Can someone help me. Which pythonic way to do it?

You can bypass all the list operations with slicing:
S = S[:1] + S[2:]
or more generally
S = S[:Index] + S[Index + 1:]
Many answers to your question (including ones like this) can be found here: How to delete a character from a string using python?. However, that question is nominally about deleting by value, not by index.

Slicing is the best and easiest approach I can think of, here are some other alternatives:
>>> s = 'abcd'
>>> def remove(s, indx):
return ''.join(x for x in s if s.index(x) != indx)
>>> remove(s, 1)
'acd'
>>>
>>>
>>> def remove(s, indx):
return ''.join(filter(lambda x: s.index(x) != 1, s))
>>> remove(s, 1)
'acd'
Remember that indexing is zero-based.

You can replace the Index character with "".
str = "ab1cd1ef"
Index = 3
print(str.replace(str[Index],"",1))

def missing_char(str, n):
n = abs(n)
front = str[:n] # up to but not including n
back = str[n+1:] # n+1 through end of string
return front + back

S = "abcd"
Index=1 #index of string to remove
S = S.replace(S[Index], "")
print(S)
I hope it helps!

Related

Is there an operator to specify an index "not less than 0"? [duplicate]

This question already has answers here:
Pythonic way to replace list values with upper and lower bound (clamping, clipping, thresholding)?
(2 answers)
Closed last month.
To "peek" at characters in a string preceding the current index, i, is there a one-liner for avoiding negative indices? I want n chars before the current char index of the string OR beginning of the string to current char.
My intuition says there might be something simple I can put in the same line as the list operation instead of another line to make an index. I'd rather avoid any libraries, and I'm aware a simple if check would work... Hoping there's a magic operator I missed.
>>> s = 'ABCDEFG'
>>> s[0:5]
'ABCDE'
>>> s[-5:5]
'CDE'
There is no operator for doing this, but you can achieve the same effect with max:
>>> s = 'abcdefg'
>>> i = 3
>>> s[max(i - 6, 0):i + 2]
'abcde'
How about this?
s = 'ABCDEFG'
i = 5
n = 3
print(s[max(0, i-n): i])
Output:
CDE

How to capitalize every other character in a string [duplicate]

This question already has answers here:
Capitalise every other letter in a string in Python? [closed]
(5 answers)
Closed 3 years ago.
I want the program to return ' mahir ' as 'MaHiR', I have got MHR but how do I get 'a' and 'h' at their usual place ?
I have already tried slicing but that does not work
s = 'mahir'
a = list (s)
c = a[0:5:2]
for i in range (len(c)):
print (c[i].capitalize(),end = " ")
Python's strings are immutable, calling c[i].capitalize() will not change c[i], and therefore will not change s, to modify a string you must create a new one out of it, you can use str.join with a generator expression instead:
s = 'mahir'
s = ''.join(c.upper() if i % 2 == 0 else c for i, c in enumerate(s))
print(s)
Output:
MaHiR
If you want to do it using slicing, you could convert your string to a list since lists are mutable (but the string approach above is better):
s = 'mahir'
l = list(s)
l[::2] = map(str.upper, l[::2])
s = ''.join(l)
print(s)
Output:
MaHiR

python - Replace several different characters by only one [duplicate]

This question already has answers here:
how to replace multiple characters in a string?
(3 answers)
Closed 5 years ago.
I'm looking for a way to replace some characters by another one.
For example we have :
chars_to_be_replaced = "ihgr"
and we want them to be replaced by
new_char = "b"
So that the new string
s = "im hungry"
becomes
s' = "bm bunbby".
I'm well aware you can do this one char at a time with .replace or with regular expressions, but I'm looking for a way to go only once through the string.
Does the re.sub goes only once through the string ? Are there other ways to do this ? Thanks
Thanks
You can use string.translate()
from string import maketrans
chars_to_be_replaced = "ihgr"
new_char = "b"
s = "im hungry"
trantab = maketrans(chars_to_be_replaced, new_char * len(chars_to_be_replaced))
print s.translate(trantab)
# bm bunbby
How about this:
chars_to_be_replaced = "ihgr"
new_char = "b"
my_dict = {k: new_char for k in chars_to_be_replaced}
s = "im hungry"
new_s = ''.join(my_dict.get(x, x) for x in s)
print(new_s) # bm bunbby
''.join(my_dict.get(x, x) for x in s): for each letter in your original string it tries to get it's dictionary value instead unless it does not exist in which case the original is returned.
NOTE: You can speed it up (a bit) by passing a list to join instead of a generator:
new_s = ''.join([my_dict.get(x, x) for x in s])

Python - making a function that would add "-" between letters

I'm trying to make a function, f(x), that would add a "-" between each letter:
For example:
f("James")
should output as:
J-a-m-e-s-
I would love it if you could use simple python functions as I am new to programming. Thanks in advance. Also, please use the "for" function because it is what I'm trying to learn.
Edit:
yes, I do want the "-" after the "s".
Can I try like this:
>>> def f(n):
... return '-'.join(n)
...
>>> f('james')
'j-a-m-e-s'
>>>
Not really sure if you require the last 'hyphen'.
Edit:
Even if you want suffixed '-', then can do like
def f(n):
return '-'.join(n) + '-'
As being learner, it is important to understand for your that "better to concat more than two strings in python" would be using str.join(iterable), whereas + operator is fine to append one string with another.
Please read following posts to explore further:
Any reason not to use + to concatenate two strings?
which is better to concat string in python?
How slow is Python's string concatenation vs. str.join?
Also, please use the "for" function because it is what I'm trying to learn
>>> def f(s):
m = s[0]
for i in s[1:]:
m += '-' + i
return m
>>> f("James")
'J-a-m-e-s'
m = s[0] character at the index 0 is assigned to the variable m
for i in s[1:]: iterate from the second character and
m += '-' + i append - + char to the variable m
Finally return the value of variable m
If you want - at the last then you could do like this.
>>> def f(s):
m = ""
for i in s:
m += i + '-'
return m
>>> f("James")
'J-a-m-e-s-'
text_list = [c+"-" for c in text]
text_strung = "".join(text_list)
As a function, takes a string as input.
def dashify(input):
output = ""
for ch in input:
output = output + ch + "-"
return output
Given you asked for a solution that uses for and a final -, simply iterate over the message and add the character and '-' to an intermediate list, then join it up. This avoids the use of string concatenations:
>>> def f(message)
l = []
for c in message:
l.append(c)
l.append('-')
return "".join(l)
>>> print(f('James'))
J-a-m-e-s-
I'm sorry, but I just have to take Alexander Ravikovich's answer a step further:
f = lambda text: "".join([c+"-" for c in text])
print(f('James')) # J-a-m-e-s-
It is never too early to learn about list comprehension.
"".join(a_list) is self-explanatory: glueing elements of a list together with a string (empty string in this example).
lambda... well that's just a way to define a function in a line. Think
square = lambda x: x**2
square(2) # returns 4
square(3) # returns 9
Python is fun, it's not {enter-a-boring-programming-language-here}.

Finding substring in python [duplicate]

This question already has answers here:
Python: Find a substring in a string and returning the index of the substring
(7 answers)
Closed 2 years ago.
I'm new to python and I'm trying different methods to accomplish the same task, right now I'm trying to figure out how to get a substring out of a string using a for loop and a while loop. I quickly found that this is a really easy task to accomplish using regex. For example if I have a string: "ABCDEFGHIJKLMNOP" and I want to find if "CDE" exists then print out "CDE" + the rest of the string how would I do that using loops? Right now I'm using:
for i, c in enumerate(myString):
which returns each index and character, which I feel is a start but I can't figure out what to do after. I also know there are a lot of build in functions to find substrings by doing: myString.(Function) but I would still like to know if it's possible doing this with loops.
Given:
s = 'ABCDEFGHIJKLMNOP'
targets = 'CDE','XYZ','JKL'
With loops:
for t in targets:
for i in range(len(s) - len(t) + 1):
for j in range(len(t)):
if s[i + j] != t[j]:
break
else:
print(s[i:])
break
else:
print(t,'does not exist')
Pythonic way:
for t in targets:
i = s.find(t)
if i != -1:
print(s[i:])
else:
print(t,'does not exist')
Output (in both cases):
CDEFGHIJKLMNOP
XYZ does not exist
JKLMNOP
Here's a concise way to do so:
s = "ABCDEFGHIJKLMNOP"
if "CDE" in s:
print s[s.find("CDE")+len("CDE"):]
else:
print s
Prints:
FGHIJKLMNOP
The caveat here is of course, if the sub-string is not found, the original string will be returned.
Why do this? Doing so allows you to check whether or not the original string was found or not. As such, this can be conceptualized into a simple function (warning: no type checks enforced for brevity - it is left up to the reader to implement them as necessary):
def remainder(string, substring):
if substring in string:
return string[string.find(substring)+len(substring):]
else:
return string
Getting the remainder of the string using a for-loop:
n = len(substr)
rest = next((s[i+n:] for i in range(len(s) - n + 1) if s[i:i+n] == substr),
None) # return None if substr not in s
It is equivalent to:
_, sep, rest = s.partition(substr)
if substr and not sep: # substr not in s
rest = None

Categories

Resources