Select part of a string and change it in lowercase or uppercase python 3.x - string

I want to convert a string so that the pair positions will be in upper case characters and the impair positions will be in lower case characters.
Here is what I've tried so far:
def foldingo(chaine):
chaineuh=chaine[0::2].upper()
chaine=chaineuh[1::2].lower()
return chaine

your code takes every other character in chaine, uppercases them, and assigns those characters to chaineuh.
Then it takes every other character in chaineuh, lowercases them, and assigns those characters to chaine again. In other words:
abcdefg -> ACEG -> cg
You'll notice it's not keeping the characters that you're not trying to target.
You could try building all the uppercases and lowercases separately, then iterate with zip to get them together.
def fold(s):
uppers = s[0::2].upper()
lowers = s[1::2].lower()
return zip(uppers, lowers)
But this doesn't quit work either, since zip gives you tuples, not strings, and will drop the last character in odd-lengthed strings
abcdefg -> ACEG, bdf -> ('A', 'b'), ('C', 'd'), ('E', 'f')
We could fix that by using a couple calls to str.join and using itertools.zip_longest with a fillvalue='', but it's kind of like using a wrench to hammer in a nail. It's not really the right tool for the job. For the record: it would look like:
''.join([''.join(pair) for pair in itertools.zip_longest(uppers, lowers, fillvalue='')])
yuck.
Let's instead just iterate over the string and uppercase every other letter. We can use an alternating boolean to track whether we're upper'ing or lower'ing this time around.
def fold(s):
time_to_upper = True
result = ""
for ch in s:
if time_to_upper:
result += ch.upper()
else:
result += ch.lower()
time_to_upper = not time_to_upper
return result
You could also use enumerate and a modulo to keep track:
def fold(s):
result = ""
for i, ch in enumerate(s):
ch = ch.lower() if i % 2 else ch.upper()
result += ch
return result
Or by using itertools.cycle, str.join, and list comprehensions, we can make this a lot shorter (possibly at the cost of readability!)
import itertools
def fold(s):
return ''.join([op(ch) for op, ch in zip(itertools.cycle([str.upper, str.lower]), s)]

Related

Replace string only if all characters match (Thai)

The problem is that มาก technically is in มาก็. Because มาก็ is มาก + ็.
So when I do
"แชมพูมาก็เยอะ".replace("มาก", " X ")
I end up with
แชมพู X ็เยอะ
And what I want
แชมพู X เยอะ
What I really want is to force the last character ก็ to count as a single character, so that มาก no longer matches มาก็.
While I haven't found a proper solution, I was able to find a solution. I split each string into separate (combined) characters via regex. Then I compare those lists to each other.
# Check is list is inside other list
def is_slice_in_list(s,l):
len_s = len(s) #so we don't recompute length of s on every iteration
return any(s == l[i:len_s+i] for i in range(len(l) - len_s+1))
def is_word_in_string(w, s):
a = regex.findall(u'\X', w)
b = regex.findall(u'\X', s)
return is_slice_in_list(a, b)
assert is_word_in_string("มาก็", "พูมาก็เยอะ") == True
assert is_word_in_string("มาก", "พูมาก็เยอะ") == False
The regex will split like this:
พู ม า ก็ เ ย อ ะ
ม า ก
And as it compares ก็ to ก the function figures the words are not the same.
I will mark as answered but if there is a nice or "proper" solution I will chose that one.

How to split string by odd length

Lets say with a string = "AABBAAAAABBBBAAABBBBAA"
I want to return string split by the odd lengths of the string (i.e when A = 5 or A = 3),
What I want returned is 1) AABBAAAAA 2)BBBBAAA 3)BBBBAA,
How can I do that?
I tried using regex [A]+[B]+ for a slightly different case
One option might be to regex iterate using re.finditer with the following pattern:
.*?(?:AAA(?:AA)?|$)
This pattern will non greedily consume until reaching either 3 A's, 5 A's, or the end of the string. Then, we can print out each complete match as we iterate.
input = 'AABBAAAAABBBBAAABBBBAA'
pattern = '.*?(?:AAA(?:AA)?|$)'
for match in re.finditer(pattern, input):
print match.group()
This prints:
AABBAAAAA
BBBBAAA
BBBBAA
You can use itertools.groupby:
s = 'BBAAAAABBBBAAABBBBAA'
from itertools import groupby
out = ['']
for v, g in groupby(s):
l = [*g]
out[-1] += ''.join(l)
if v == 'A' and len(l) in (3, 5):
out.append('')
print(out)
Prints:
['BBAAAAA', 'BBBBAAA', 'BBBBAA']

hello friends i cant execute my else condition

The program must accept a string S as the input. The program must replace every vowel in the string S by the next consonant (alphabetical order) and replace every consonant in the string S by the next vowel (alphabetical order). Finally, the program must print the modified string as the output.
s=input()
z=[let for let in s]
alpa="abcdefghijklmnopqrstuvwxyz"
a=[let for let in alpa]
v="aeiou"
vow=[let for let in v]
for let in z:
if(let=="a"or let=="e" or let=="i" or let=="o" or let=="u"):
index=a.index(let)+1
if index!="a"or index!="e"or index!="i"or index!="o"or index!="u":
print(a[index],end="")
else:
for let in alpa:
ind=alpa.index(let)
i=ind+1
if(i=="a"or i=="e" or i=="i"or i=="o"or i=="u"):
print(i,end="")
the output is :
i/p orange
pbf
the required output is:
i/p orange
puboif
I would do it like this:
import string
def dumb_encrypt(text, vowels='aeiou'):
result = ''
for char in text:
i = string.ascii_letters.index(char)
if char.lower() in vowels:
result += string.ascii_letters[(i + 1) % len(string.ascii_letters)]
else:
c = 'a'
for c in vowels:
if string.ascii_letters.index(c) > i:
break
result += c
return result
print(dumb_encrypt('orange'))
# puboif
Basically, I would use string.ascii_letters, instead of defining that anew. Also, I would not convert all to list as it is not necessary for looping through. The consonants you got right. The vowels, I would just do an uncertain search for the next valid consonant. If the search, fails it sticks back to default a value.
Here I use groupby to split the alphabet into runs of vowels and consonants. I then create a mapping of letters to the next letter of the other type (ignoring the final consonants in the alphabet). I then use str.maketrans to build a translation table I can pass to str.translate to convert the string.
from itertools import groupby
from string import ascii_lowercase as letters
vowels = "aeiou"
is_vowel = vowels.__contains__
partitions = [list(g) for k, g in groupby(letters, is_vowel)]
mapping = {}
for curr_letters, next_letters in zip(partitions, partitions[1:]):
for letter in curr_letters:
mapping[letter] = next_letters[0]
table = str.maketrans(mapping)
"orange".translate(table)
# 'puboif'

Zipping strings together at arbitrary index and step (Python)

I am working in Python 2.7. I am trying to create a function which can zip a string into a larger string starting at an arbitrary index and with an arbitrary step.
For example, I may want to zip the string ##*#* into the larger string TNAXHAXMKQWGZESEJFPYDMYP starting at the 5th character with a step of 3. The resulting string should be:
TNAXHAX#MK#QW*GZ#ES*EJFPYDMYP
The working function that I came up with is
#Insert one character of string every nth position starting after ith position of text
text="TNAXHAXMKQWGZESEJFPYDMYP"
def zip_in(string,text,i,n):
text=list(text)
for c in string:
text.insert(i+n-1,c)
i +=n
text = ''.join(text)
print text
This function produces the desired result, but I feel that it is not as elegant as it could be.
Further, I would like it to be general enough that I can zip in a string backwards, that is, starting at the ith position of the text, I would like to insert the string in one character at a time with a backwards step.
For example, I may want to zip the string ##*#* into the larger string TNAXHAXMKQWGZESEJFPYDMYP starting at the 22nd position with a step of -3. The resulting string should be:
TNAXHAXMKQW*GZ#ES*EJ#FP#YDMYP
With my current function, I can do this by setting n negative, but if I want a step of -3, I need to set n as -2.
All of this leads me to my question:
Is there a more elegant (or Pythonic) way to achieve my end?
Here are some related questions which don't provide a general answer:
Pythonic way to insert every 2 elements in a string
Insert element in Python list after every nth element
Merge Two strings Together at N & X
You can use some functions from the itertools and more_itertools libraries (make sure to have them) and combine them to get your result : chunked and izip_longest.
# Parameters
s1 = 'ABCDEFGHIJKLMNOPQ' # your string
s2 = '####' # your string of elements to add
int_from = 4 # position from which we start adding letters
step = 2 # we will add in elements of s2 each 2 letters
return_list = list(s1)[:int_from] # keep the first int_from elements unchanged
for letter, char in izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue=''):
return_list.extend(letter)
return_list.append(char)
Then get your string back by doing :
''.join(return_list)
Output :
# For the parameters above the output is :
>> 'ABCDEF#GH#IJ#KL#MNOPQ'
What does izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue='') return ?:
for letter, char in izip_longest(chunked(list(s1)[int_from:], step), s2, fillvalue=''):
print(letter, char)
>> Output
>> (['E', 'F'], '#')
(['G', 'H'], '#')
(['I', 'J'], '#')
(['K', 'L'], '#')
(['M', 'N'], '')
(['O', 'P'], '')
(['Q'], '')

How can I delete the letter that occurs in the two strings using python?

That's the source code:
def revers_e(str_one,str_two):
for i in range(len(str_one)):
for j in range(len(str_two)):
if str_one[i] == str_two[j]:
str_one = (str_one - str_one[i]).split()
print(str_one)
else:
print('There is no relation')
if __name__ == '__main__':
str_one = input('Put your First String: ').split()
str_two = input('Put your Second String: ')
print(revers_e(str_one, str_two))
How can I remove a letter that occurs in both strings from the first string then print it?
How about a simple pythonic way of doing it
def revers_e(s1, s2):
print(*[i for i in s1 if i in s2]) # Print all characters to be deleted from s1
s1 = ''.join([i for i in s1 if i not in s2]) # Delete them from s1
This answer says, "Python strings are immutable (i.e. they can't be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings."
First of all you don't need to use a pretty suboptimal way using range and len to iterate over a string since strings are iterable you can just iterate over them with a simple loop.
And for finding intersection within 2 string you can use set.intersection which returns all the common characters in both string and then use str.translate to remove your common characters
intersect=set(str_one).intersection(str_two)
trans_table = dict.fromkeys(map(ord, intersect), None)
str_one.translate(trans_table)
def revers_e(str_one,str_two):
for i in range(len(str_one)):
for j in range(len(str_two)):
try:
if str_one[i] == str_two[j]:
first_part=str_one[0:i]
second_part=str_one[i+1:]
str_one =first_part+second_part
print(str_one)
else:
print('There is no relation')
except IndexError:
return
str_one = input('Put your First String: ')
str_two = input('Put your Second String: ')
revers_e(str_one, str_two)
I've modified your code, taking out a few bits and adding a few more.
str_one = input('Put your First String: ').split()
I removed the .split(), because all this would do is create a list of length 1, so in your loop, you'd be comparing the entire string of the first string to one letter of the second string.
str_one = (str_one - str_one[i]).split()
You can't remove a character from a string like this in Python, so I split the string into parts (you could also convert them into lists like I did in my other code which I deleted) whereby all the characters up to the last character before the matching character are included, followed by all the characters after the matching character, which are then appended into one string.
I used exception statements, because the first loop will use the original length, but this is subject to change, so could result in errors.
Lastly, I just called the function instead of printing it too, because all that does is return a None type.
These work in Python 2.7+ and Python 3
Given:
>>> s1='abcdefg'
>>> s2='efghijk'
You can use a set:
>>> set(s1).intersection(s2)
{'f', 'e', 'g'}
Then use that set in maketrans to make a translation table to None to delete those characters:
>>> s1.translate(str.maketrans({e:None for e in set(s1).intersection(s2)}))
'abcd'
Or use list comprehension:
>>> ''.join([e for e in s1 if e in s2])
'efg'
And a regex to produce a new string without the common characters:
>>> re.sub(''.join([e for e in s1 if e in s2]), '', s1)
'abcd'

Resources