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"));
Related
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)
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.
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 3 years ago.
Improve this question
I'm creating a search feature of a web site. I need to extract an user input kind of a sentence to a list but requires words in quotes should be an item of the list.
Please focus on the words Jeff Watson and New York in my expectation.
Expectation:
str = 'Hello, I am "Jeff Watson" from a part of "New York".'
result = ["Hello", "I", "am", "Jeff Watson", "from", "a", "part", "of", "New York"]
It's the best if your answer works with single quotes as well.
A regexp looking for either quoted substrings or words:
import re
string = 'Hello, I am "Jeff Watson" from NY.'
[next(x for x in m if x)
for m in re.findall(r'"([^"]*)"|\'([^\']*)\'|(\w+)', string)]
(Also, try to avoid using str as a variable name in Python, as it normally holds the string type.)
Here's another method:
[m[1] for m in re.findall(r'(["\'])?((?(1).*?\1|\w+))', string)]
a very rookie solution
s = 'Hello, I am "Jeff Watson" from NY.'
ans = []
i = 0
while i < len(s):
if s[i].isalnum():
temp = ""
while s[i].isalnum():
temp += s[i]
i += 1
ans.append(temp)
if s[i] == '"':
temp = '"'
i += 1
while s[i] != '"':
temp += s[i]
i += 1
temp += '"'
ans.append(temp)
i += 1
print(ans)
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
Code only runs for one word and not the whole string
def silly_case(in_string):
firstlet = in_string[0]
firstlet = firstlet.lower()
upperpart = in_string[1:]
upperpart = upperpart.upper()
in_string = firstlet + upperpart
return in_string
silly_string = silly_case("This is a string")
print(silly_string)
You can use the built-in functions title and swapcase:
>>> "This is a string".title().swapcase()
'tHIS iS a sTRING'
Or to fix your code, you should split the string into words and then iterate through them before you apply your case logic on each word:
def silly_case(in_string):
words = []
for word in in_string.split():
firstlet = word[0]
firstlet = firstlet.lower()
upperpart = word[1:]
upperpart = upperpart.upper()
words.append(firstlet + upperpart)
return ' '.join(words)
silly_string = silly_case("This is a string")
print(silly_string)
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 years ago.
Improve this question
Here is the code I have tried so far:
s = 'abcabcde'
count = 0
for letter in s:
if letter in 'aeiou':
count += 1
print ('Number of vowels: ' + str(count))
For an explicit loop-based solution, you can do the following:
seen = set()
s = 'abcabcde'
for c in s:
if c in 'aeiou':
seen.add(c)
print ('Number of vowels: ' + len(seen))
Or more concisely, using set intersection:
count = len(set('aeiou') & set('abcabcde'))
vcount = lambda txt: sum([1 for i in 'aeiou' if i in txt])
print(vcount('fox'), vcount('eating')
1 3
This should do it:
vowels = set(['a','e','i','o','u'])
s = 'abcabcde'
set_s = set(s)
print ('Number of vowels: ' + str(len(vowels & set_s)))
Gives
2