This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to replace a string in a function with another string in Python?
I want to enter any string with any type of character, and if the character is an alphabet, I want to replace it with "^" and get it printed.
For example, if my input is replace('text-here'), I should get the output as "^^^^-^^^^".
I've tried using the following statement, but it just prints whatever my input was. Please help!
def replace(string):
for x in range(len(string)):
string.replace(string[x],"^")
print(string)
I'm new to python, and don't know complex stuff. Please give me easy-to-understand answers. Thanks!
>>> text = 'text-here'
>>> ''.join('^' if c.isalpha() else c for c in text)
'^^^^-^^^^'
I think this is easy to understand but just in case here is code that shows what it does more simply:
>>> def replace(text):
new_text = ''
for c in text:
if c.isalpha():
new_text += '^'
else:
new_text += c
return new_text
>>> replace(text)
'^^^^-^^^^'
You could use Python's Regular Expressions library.
Like so,
import re
re.sub('\w', '^', 'text-here')
# Outputs: "^^^^-^^^^"
That's because string is immutable. string.replace(string[x],"^") returns a new object.
Modify
string.replace(string[x],"^")
to
string = string.replace(string[x],"^")
and it will work as expected.
Now that your question is on "but it just prints whatever my input was", I would like to tell you that the method str.replace will return a new string instead of to replace the string in place.
>>> a = "foo"
>>> a.replace("foo","bar")
'bar'
>>> a
'foo'
So you need to do string = string.replace(...)
Related
This question already has answers here:
Find common characters between two strings
(5 answers)
Closed 2 months ago.
I have a string of text
hfHrpphHBppfTvmzgMmbLbgf
I have separated this string into two half's
hfHrpphHBppf,TvmzgMmbLbgf
I'd like to check if any of the characters in the first string, also appear in the second string, and would like to class lowercase and uppercase characters as separate (so if string 1 had a and string 2 had A this would not be a match).
and the above would return:
f
split_text = ['hfHrpphHBppf', 'TvmzgMmbLbgf']
for char in split_text[0]:
if char in split_text[1]:
print(char)
There is probably a better way to do it, but this a quick and simple way to do what you want.
Edit:
split_text = ['hfHrpphHBppf', 'TvmzgMmbLbgf']
found_chars = []
for char in split_text[0]:
if char in split_text[1] and char not in found_chars:
found_chars.append(char)
print(char)
There is almost certainly a better way of doing this, but this is a way of doing it with the answer I already gave
You could use the "in" word.
something like this :
for i in range(len(word1) :
if word1[i] in word2 :
print(word[i])
Not optimal, but it should print you all the letter in common
You can achieve this using set() and intersection
text = "hfHrpphHBppf,TvmzgMmbLbgf"
text = text.split(",")
print(set(text[0]).intersection(set(text[1])))
You can use list comprehension in order to check if letters from string a appears in string b.
a='hfHrpphHBppf'
b='TvmzgMmbLbgf'
c=[x for x in a if x in b]
print(' '.join(set(c)))
then output will be:
f
But you can use for,too. Like:
a='hfHrpphHBppf'
b='TvmzgMmbLbgf'
c=[]
for i in a:
if i in b:
c.append(i)
print(set(c))
I want to loop through a string and when it finds an uppercase letter, I want to replace it with #. Like this:
string = "hOw Are yOu?"
for x in string:
if x.isupper():
string.replace(x, "#")
print(string)
else:
print(string)
However, its not working as intended and is instead outputting the same string. Do tell me if there is a way to fix this or if you'd suggest another way.
Use list comprehension with join:
In [4]: ''.join([i if not i.isupper() else '#' for i in string])
Out[4]: 'h#w #re y#u?'
You just want to put the result again in string see below
string = "hOw Are yOu?"
for x in string:
if x.isupper():
string = string.replace(x, "#")
print(string)
else:
print(string)
Strings are immutable in Python. string.replace(x, "#") must thus be string = string.replace(x, "#") to have an effect on the string.
Note that currently your code has quadratic complexity as each replace operation has to loop over the entire string in linear time. A more efficient approach would be to perform the replacements yourself, as you're already looping over every character:
string = "".join(["#" if c.isupper() else c for c in "hOw Are yOu?"])
it would be even more concise (and possibly faster) to use a very simple RegEx for this:
import re
string = re.sub("[A-Z]", "#", "hOw Are yOu?")
this will fail for non-ASCII alphabets however; you'd have to use unicode properties & regex there.
This should do the trick!
string = "hOw Are yOu?"
for x in string:
if x.isupper():
string = string.replace(x, "#")
else:
pass
print(string)
I'm a novice as well! But from what I learned: when doing loops or if statements, you want to specify the value you are changing as I did in line 4 with: string = string.replace(x,'#') If not the change will not take effect!
Example:
my_list = [1,2,3,4]
for x in my_list:
my_list[x-1] = x + 1
print(my_list)
This is a poor example coding wise but it exemplifies the concept. If you don't address the variable it wont have any effect on it!
Hope this helps!
This question already has answers here:
Python replace string pattern with output of function
(4 answers)
Closed 5 years ago.
Say I have the following string:
mystr = "6374696f6e20????28??????2c??2c????29"
And I want to replace every sequence of "??" with its length\2. So for the example above, I want to get the following result:
mystr = "6374696f6e2022832c12c229"
Meaning:
???? replaced with 2
?????? replaced with 3
?? replaced with 1
???? replaced with 2
I tried the following but I'm not sure it's the good approach, and anyway -- it doesn't work:
regex = re.compile('(\?+)')
matches = regex.findall(mystr)
if matches:
for match in matches:
match_length = len(match)/2
if (match_length > 0):
mystr= regex .sub(match_length , mystr)
You can use a callback function in Python's re.sub. FYI lambda expressions are shorthand to create anonymous functions.
See code in use here
import re
mystr = "6374696f6e20????28??????2c??2c????29"
regex = re.compile(r"\?+")
print(re.sub(regex, lambda m: str(int(len(m.group())/2)), mystr))
There seems to be uncertainty about what should happen in the case of ???. The above code will result in 1 since it converts to int. Without int conversion the result would be 1.0. If you want to ??? to become 1? you can use the pattern (?:\?{2})+ instead.
This question already has answers here:
Python Regex to find a string in double quotes within a string
(6 answers)
Closed 6 years ago.
I'm trying to write a function where the input has a keyword that occurs multiple times in a string and will print the stuff that has double quotation marks between them after the keyword. Essentially...
Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
Output= someonehelpmepls
itonlygivesmeoneinsteadofmultiple
If its possible to have the outputs as its own line that would be better.
Here's what I have so far:
def getEm(s):
h = s.find('keyword')
if h == -1
return -1
else:
begin = s.find('"',h)
end = s.find('"', begin+1)
result = s[begin +1:end]
print (result)
Please don't suggest import. I do not know how to do that nor know what it is, I am a beginner.
Let's take some sample input:
>>> Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
I believe that one " was missing from the sample input, so I added it.
As I understand it, you want to get the strings in double-quotes that follow the word keyword. If that is the case, then:
def get_quoted_after_keyword(input):
results = []
split_by_keyword = input.split('keyword')
# you said no results before the keyword
for s in split_by_keyword[1:]:
split_by_quote = s.split('"')
if len(split_by_quote) > 1:
# assuming you want exactly one quoted result per keyword
results.append(split_by_quote[1])
return results
>print('\n'.join(get_quoted_after_keyword(Input))
>someonehelpmepls
>itonlygivesmeoneinsteadofmultiple
How it works
Let's look at the first piece:
>>> Input.split('keyword')
['alkfjjie',
' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
By splitting Input on keyword, we get, in this case, three strings. The second string to the last are all strings that follow the word keyword. To get those strings without the first string, we use subscripting:
>>> Input.split('keyword')[1:]
[' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
Now, our next task is to get the part of these strings that is in double-quotes. To do that, we split each of these strings on ". The second string, the one numbered 1, will be the string in double quotes. As a simpler example, let's take these strings:
>>> [s.split('"')[1] for s in ('"one"otherstuff', ' "two"morestuff')]
['one', 'two']
Next, we put these two steps together:
>>> [s.split('"')[1] for s in Input.split('keyword')[1:]]
['someonehelpmepls', 'itonlygivesmeoneinsteadofmultiple']
We now have the strings that we want. The last step is to print them out nicely, one per line:
>>> print('\n'.join(s.split('"')[1] for s in Input.split('keyword')[1:]))
someonehelpmepls
itonlygivesmeoneinsteadofmultiple
Limitation: this approach assumes that keyword never appears inside the double-quoted strings.
This question already has answers here:
Changing one character in a string
(15 answers)
Closed 8 years ago.
Im trying to make a Hangman game and I need to change certain characters in a string.
Eg: '-----', I want to change the third dash in this string, with a letter. This would need to work with a word of any length, any help would be greatly appreciated
Strings are immutable, make it a list and then replace the character, then turn it back to a string like so:
s = '-----'
s = list(s)
s[2] = 'a'
s = ''.join(s)
String = list(String)
String[0] = "x"
String = str(String)
Will also work. I am not sure which one (the one with .join and the one without) is more efficient
You can do it using slicing ,
>>> a
'this is really string'
>>> a[:2]+'X'+a[3:]
'thXs is really string'
>>>