How do I put characters inbetween characters [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
word2 = input("put in the word you want me to repeat: ")
letter = ""
print("The original string is: " + word2)
for x in range(len(word2)):
letter += word2[x]
So if i put in "dwas" it will just print "dwas". How do I make it print "d-ww-aaa-ssss"?

You can use enumerate passing the string value from input, and the start value as 1, then repeat the characters n times, and finally join by -:
>>> print('-'.join(v*i for v,i in enumerate(inp,1)))
d-ww-aaa-ssss

By composiing built-in functions:
s = "hallo"
new_s = '-'.join(map(str.__mul__, s, range(1, len(s)+1)))
print(new_s)
#h-aa-lll-llll-ooooo
A for loop approach similar to the one in the question
s = "hallo"
# construct the output character per character
new_s = ''
# iterate over (index, character)-pairs, index start from 1
for i, char in enumerate(s, 1):
# add to output i-times the same character followed by -
new_s += f'{char*i}-'
# remove the last character (always the -)
new_s = new_s.rstrip('-')
# check result
print(new_s)

Related

replace text python 2 leters replace [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I only want to change the text when there are both letters
def replaceonce(s, letters = '', replacewith=''):
letters = set(letters)
res = ''
for l in s:
if l in letters:
res += replacewith
letters.remove(l)
replacewith = ''
else:
res += l
return res
print(replaceonce('yday',letters='ya',replacewith='z'))
this code change to zdy although there is a letter and is not in text
print(replaceonce('yday',letters='ya',replacewith='z'))
output
ydz or dyz or zyd all combinations are ok fine
I want the text to change as well
that it will look like this
azdry
output
or another order of letters
zdrz
if two letters will appear in the text to change only if there are both letters, so y + and in this example
The following code returns the expected outputs for both the examples:
def findIndexes(string, letters):
indexes = []
for c in letters:
for i in range(len(string)):
if string[i] == c:
indexes.append(i)
break
return indexes
def replaceonce(s, letters = '', replacewith=''):
allPresent = True
toRet = ''
# checking if all letters' chars are in s
for c in letters:
if c not in s:
allPresent = False
break
if allPresent:
# this block make the substitution
# getting the index of first occurrence of each
# letters' char inside the s string
indexes = findIndexes(s, letters)
for i in range(len(s)):
if i not in indexes:
toRet += s[i]
toRet += replacewith
return toRet
Your examples make the substitution for one occurrence of the letters string, even if the string is splitted somewhere inside the s. Then the idea is: find the index where this chars are and skip all of them when reconstruct the s string. At the end of code, add the replaceWith at the end of reconstructed string.
I hope that I understood correctly your question that, by the way, was not very clear.

Sort the sequence alphabetically-Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I want to write a python function that accepts a hyphen separated sequence of colors as input and returns the colors in a hyphen separated sequence after sorting them alphabetically
constraint: All colors will be completely in either lower case or upper case
sample input: green-red-yellow-black-white
sample output: black-green-red-white-yellow
My code -
my_str = input("Enter a string: ")
words = [word.lower() for word in my_str.split()]
words.sort()
print("The sorted words are:")
for word in words:
print(word)
This works -
def str_sort(string):
b = string.split('-')
b.sort()
c = '-'.join(b)
return c
a = input('Enter a sequence of colors separated with hyphen: ')
str_sort(a)
This will solve your problem:
inputs = "green-red-yellow-black-white"
def sort_inputs(inputs):
inputs_list = inputs.split('-')
sorted_input = sorted(inputs_list)
final = "-".join(term for term in sorted_input)
return final
final = sort_inputs(inputs)
print(final)

How do I add "_" to a string after every Capital letter? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I would like to add underscore "_" after every capital letter in a string.
For example, If the string is "StackOverFlow", I would like to make it this "_Stack_Over_Flow"
You could use a regular expression:
import re
s = "StackOverFlow"
result = re.sub(r"([A-Z])", r"_\1", s)
A simple for with isupper:
In [1722]: s = "StackOverFlow"
In [1740]: l = []
In [1741]: for c,i in enumerate(list(s)):
...: if i.isupper():
...: l.append('_' + i)
...: else:
...: l.append(i)
...:
In [1747]: s = ''.join(l)
In [1748]: s
Out[1748]: '_Stack_Over_Flow'
OR List Comprehension:
s = ''.join(['_' + i if i.isupper() else i for c,i in enumerate(list(s))])
Eh it's not much but here's a simple way.
string = "StackOverFlow"
newString = []
for letters in string:
if letters.isupper():
letters = "_"+letters
newString.append(letters)
print(''.join(newString))
Output:
_Stack_Over_Flow
Here is the function that does exactly what you asked in the question
def adding_beforeCapitalLetters(n):
newstring=''
for i in range(0,len(n)):
if (n[i]>='A' and n[i]<='Z'):
newstring = newstring + '_' + n[i]
else:
newstring = newstring + n[i];
return newstring;
print(adding_beforeCapitalLetters("StackOverFlow"));

How to move the last letter of a string to the front? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm doing the challenge in groklearning but I can't seem to figure out how to do this.
My program needs to do a few things:
Check if word ends in ay, if it does:
Remove the ay from the end of the word
Move the (now) last letter to the front of the word.
Print out the new word.
I don't know how to move the letter to the front. This is my code so far:
word = input('Word: ')
if 'ay' in word:
word1 = word[-1] + word[:-1]
word2 = word1[2:]
word3 = word2[-1] + word2[:-1]
print(word3)
else:
print(word)
If I were to type in 'athsmay' for the input, it sends out 'athsm'. Thanks in advance!
You can explicitly test that the word ends with 'ay', and do the concatenation in one line:
>>> def rearrange(word):
... if word.endswith('ay'):
... word = word[-3] + word[:-3]
... return word
...
>>> rearrange('athsmay')
'maths'
Based on the rules you gave:
Pop off 'ay' from the end, giving 'athsm'
Move the last letter of that result to the front
word[-3] uses negative indexing, where word[-1] is the last letter in the word. word[:-3] is the slice up to but not including that letter.

How to replace single word in string not replacing other with same chars [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have this code:
s = 'letter of letters'
for i in s.split(" "):
if len(i) > 4:
s = s.replace(i, i[::-1])
print s
But this prints "rettel of rettels" which means code replace all 'letter' in string, but i need to replace only by every word themself.
How it possible to chagne single word but not all in string? I need 'rettel of srettel'
You need to collect all the modified words separately, instead of modifying the string in your loop:
words = s.split(' ')
results = []
for word in words:
if len(word) > 4:
results.append(word[::-1])
else:
results.append(word)
print(' '.join(results))

Categories

Resources