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
Related
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
This question already has answers here:
Changing one character in a string
(15 answers)
Closed 2 years ago.
I have a list called x below and I want to replace the ">" (in x[0][0]) with the integer 1.
x = [">000#","#0#00","00#0#"]
I tried x[0][0] = 1 but it gives me an error.
Also, can I make x[0][2] to become an integer such that
x[0][2] += 1 becomes this:
x = ["1010#","#0#00","00#0#"]
You can try
x[0]=x[0].replace(">","1")
Strings are immutable so cant be changed like list.
Or you can convert to list.
x[0]=list(x[0])
x[0][0]="1"
x[0][2]=str(int(x[0][2])+1)
x[0]="".join(x[0])
Python strings are immutable; you cannot change their contents. Instead, you need to make a new string out of the old one and assign that to x[0]:
x = [">000#","#0#00","00#0#"]
# change the first character to a '1'
x[0] = '1' + x[0][1:]
# add 1 to the third character
x[0] = x[0][:2] + str(int(x[0][2]) + 1) + x[0][3:]
print(x)
Output:
['1010#', '#0#00', '00#0#']
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])
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!
This question already has answers here:
How can I find all common letters in a set of strings?
(2 answers)
Closed 8 years ago.
I need to make a function that takes two string arguments and returns a string with only the characters that are in both of the argument strings. There should be no duplicate characters in the return value.
this is what I have but I need to make it print things only once if there is more then one
def letter(x,z):
for i in x:
for f in z:
if i == f:
s = str(i)
print(s)
If the order is not important, you can take the intersection & of the set of characters in each word, then join that set into a single string and return it.
def makeString(a, b):
return ''.join(set(a) & set(b))
>>> makeString('sentence', 'santa')
'nts'
Try this
s = set()
def letter(x,z):
for i in x:
for f in z:
if i == f:
s.add(i)
letter("hello","world")
print("".join(s))
It will print 'ol'
If sets aren't your bag for some reason (perhaps you want to maintain the order in one or other of the strings, try:
def common_letters(s1, s2):
unique_letters = []
for letter in s1:
if letter in s2 and letter not in unique_letters:
unique_letters.append(letter)
return ''.join(unique_letters)
print(common_letters('spam', 'arthuprs'))
(Assuming Python 3 for the print()).