How can I replace a character with a number in a string? - python

How do I place a variable in .replace() in python. For example:
x = 2
example = example2.replace("1", x)
I think its clear what I am looking for, I just have no clue how to do it.

My comments are based on Python v2.7:
In your code, "x" is assigned a integer value, they do not have replace method.
Instead, if "x" had carried normal string, then replace is available and this is how it works:
var2 = "palindrome syndrome"
print var2.replace("drome", "pal", 2)
Output:
palinpal synpal
In the statement, var2.replace, there are three arguments:
"drome" is the substring to find and replace with new string "pal" and do this for two occurrences of "drome".

Related

How to split a string with an integer into two variables?

For example, is it possible to convert the input
x = 10hr
into something like
y = 10
z = hr
I considering slicing, but the individual parts of the string will never be of a fixed length -- for example, the base string could also be something like 365d or 9minutes.
I'm aware of split() and re.match which can separate items into a list/group based on delimitation. But I'm curious what the shortest way to split a string containing a string and an integer into two separate variables is, without having to reassign the elements of the list.
You could use list comprehension and join it as a string
x='10hr'
digits="".join([i for i in x if not i.isalpha()])
letters="".join([i for i in x if i.isalpha()])
You don't need some fancy function or regex for your use case
x = '10hr'
i=0
while x[i].isdigit():
i+=1
The solution assumes that the string is going to be in format you have mentioned: 10hr, 365d, 9minutes, etc..
Above loop will get you the first index value i for the string part
>>i
2
>>x[:i]
'10'
>>x[i:]
'hr'

How can I use for loops to replace multiple characters in a string? [duplicate]

This question already has an answer here:
How can I replace multiple characters in a string using python?
(1 answer)
Closed 5 years ago.
I already asked a question exactly like this, but the answer I got still worked and it used the .translate method within the function, but I want to use "for loops" to get the output I am looking for. Here is the link to the questions I asked a while ago: How can I replace multiple characters in a string using python?
I am having some trouble figuring out how to replace multiple characters in a string using a for loop. I am trying to write a functions called replace(string) that takes in an input, and replaces certain letters in the input with another letter.
Lets say I have the string "WXYZ" and I want to replace all the W with Y, X with Z, Y with W, and Z with X. I want it to do the replacement no matter what the input is. So if I also do something like replace("WWZXWWXYYZWYYY") it should replace the letters like I said above.
This is what I have done so far with the for loops:
def replace(string):
for letters in string:
string = string.replace("W","Y").replace("X","Z").replace("Y","W").replace("Z","X")
print(string)
but when I run it with replace("WXYZ")
I get the output of the code as: WXWX
Instead of getting YZWX as the output. I also want to use the built in functions of python as well.
How can I achieve this?
The problem is that you have intersection in your replaces. Python calls the methods from the left to right. That's why the following code works:
In [6]: 'ax'.replace('a', 'b').replace('b', 'g')
Out[6]: 'gx'
For getting ride of that problem you should replace the characters at once. One way around this is using regex or even better (if you just want to replace the character) the str.translate method:
In [16]: d = {"W": "Y", "X": "Z", "Y": "W", "Z": "X"}
In [17]: "WXYZ".translate(str.maketrans(d))
Out[17]: 'YZWX'
Here is a solution to your problem. I hope this helps you :)
def replacer(string): #define the function with a parameter (which will be whatever string you want)
newlist = [] #create a new list which will be the output
strlist = list(string) #create a list of each character in the input string
for item in strlist: #iterate through the items in the list of string characters
if item == 'W': # this line and the next 7 lines check what the letter is and writes the letter you want to the new list
newlist.append('Y')
elif item == 'X':
newlist.append('Z')
elif item == 'Y':
newlist.append('W')
elif item == 'Z':
newlist.append('X')
return ''.join(newlist) #output the new list as a string
replacer('WWZXWWXYYZWYYY') #call the function with the string as a parameter
The problem is that the third replace replaces also the new Ys (that were originally Ws).
One way is to use RegEx, as in here.
Another way I can think of is to swap into temporary values. But for that you need to find temporary values that would never appear in the original string.
For example, if you know the original string would be only UPPERCASE letters, you can use string.replace("W","y").replace("X","z").replace("Y","w").replace("Z","x"), and then replace all the lowercase back into uppercase without worrying about rereplacing the letters.
If you can't be sure it'll be only uppercase, find another set of chars that will never be on the string, or use RegEx.

Error:string index out of range, defining a function

I'm practicing coding on codingbat.com since I'm a complete beginner in python, and here is one of the exercises:
Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo".
Here is my attempt at defining the function string_bits(str):
def string_bits(str):
char = 0
first = str[char]
for char in range(len(str)):
char += 2
every_other = str[char]
return (first + every_other)
Running the code gives an error. What's wrong with my code?
A different approach, with an explanation:
If you need to handle a sentence, where spaces would be included, you can do this using slicing. On a string slicing works as:
[start_of_string:end_of_string:jump_this_many_char_in_string]
So, you want to jump only every second letter, so you do:
[::2]
The first two are empty, because you just want to step every second character.
So, you can do this in one line, like this:
>>> " ".join(i[::2] for i in "Hello World".split())
'Hlo Wrd'
What just happened above, is we take our string, use split to make it a list. The split by default will split on a space, so we will have:
["Hello", "World"]
Then, what we will do from there, is using a comprehension, iterate through each item of the list, which will give us a word at a time, and from there we will perform the desired string manipulation per i[::2].
The comprehension is: (documentation)
i[::2] for i in "Hello World".split()
Finally, we call "".join (doc), which will now change our list back to a string, to finally give us the output:
"Hlo Wrd"
Check out the slicing section from the docs: https://docs.python.org/3/tutorial/introduction.html
The problem is that the char += 2 returns a value greater than len(str) as len(str)-1 (the range) + 2 is longer than the string. You could do:
def string_bits(string):
if len(string) == 2:
return string[0]
result = ''
for char in range(0,len(string),2):#range created value sin increments of two
result += string[char]
return result
A more succinct method would be:
def string_bits(string):
return string[::2]
You should avoid using 'str' as a variable name as it is a reserved word by Python.
Ok, for me:
You should not use str as a variable name as it is a python built-in function (replace str by my_str for example)
For example, 'Hello' length is 5, so 0 <= index <= 4. Here you are trying to access index 3+2=5 (when char = 3) in your for loop.
You can achieve what you want with the following code:
def string_bits(my_str):
result = ""
for char in range(0, len(my_str), 2):
result += my_str[char]
return result
The error you are getting means that you are trying to get the nth letter of a string that has less than n characters.
As another suggestion, strings are Sequence-types in Python, which means they have a lot of built-in functionalities for doing exactly what you're trying to do here. See Built-in Types - Python for more information, but know that sequence types support slicing - that is, selection of elements from the sequence.
So, you could slice your string like this:
def string_bits(input_string):
return input_string[::2]
Meaning "take my input_string from the start (:) to the end (:) and select every second (2) element"

Counting occurence within a string Python

I am writing a code to count the occurrences of each letter within a string. I understand that it has been asked and answered Count occurrence of a character in a string, however I cannot figure out why it will not count when I use it.
def percentLetters(string):
string = 'A','B'
print string.count('A')
print string.count('B')
If I was to input percentLetters('AABB'), I would anticipate receiving A=2 and B=2 but am having no such luck. I tried using an if statement earlier however it would not print anything at all
def percentLetters(string):
string='A','B'
if 'A':
print string.count('A')
if 'B':
print string.count('B')
This doesn't work either. Anyone who might have some insight it would be helpful
Don't reassign string inside the function and better to not use string as a variable name at all.
def percentLetters(s):
print s.count('A')
print s.count('B')
percentLetters('AABB')
2
2
string = 'A','B' means you set the string variable to a tuple containing just ("A","B"), it is not pointing to the string you pass in.
In [19]: string = 'A','B'
In [20]: string
Out[20]: ('A', 'B')
Because count is a method/module (whatever it's called in python) for string, the way you do it,
myString ='A','B'
myString is a tuple, not a string.
first, here is the correct version of your code:
def percentLetters(string):
print string.count('A')
print string.count('B')
second, you don't use two strings in an assignment to one variable unless you want to make it a string tuple.

Display the number of lower case letters in a string

This is what I have so far:
count=0
mystring=input("enter")
for ch in mystring:
if mystring.lower():
count+=1
print(count)
I figured out how to make a program that displays the number of lower case letters in a string, but it requires that I list each letter individually: if ch=='a' or ch=='b' or ch=='c', etc. I am trying to figure out how to use a command to do so.
This sounds like homework! Anway, this is a fun way of doing it:
#the operator module contains functions that can be used like
#their operator counter parts. The eq function works like the
#'=' operator; it takes two arguments and test them for equality.
from operator import eq
#I want to give a warning about the input function. In python2
#the equivalent function is called raw_input. python2's input
#function is very different, and in this case would require you
#to add quotes around strings. I mention this in case you have
#been manually adding quotes if you are testing in both 2 and 3.
mystring = input('enter')
#So what this line below does is a little different in python 2 vs 3,
#but comes to the same result in each.
#First, map is a function that takes a function as its first argument,
#and applies that to each element of the rest of the arguments, which
#are all sequences. Since eq is a function of two arguments, you can
#use map to apply it to the corresponding elements in two sequences.
#in python2, map returns a list of the elements. In python3, map
#returns a map object, which uses a 'lazy' evaluation of the function
#you give on the sequence elements. This means that the function isn't
#actually used until each item of the result is needed. The 'sum' function
#takes a sequence of values and adds them up. The results of eq are all
#True or False, which are really just special names for 1 and 0 respectively.
#Adding them up is the same as adding up a sequence of 1s and 0s.
#so, map is using eq to check each element of two strings (i.e. each letter)
#for equality. mystring.lower() is a copy of mystring with all the letters
#lowercase. sum adds up all the Trues to get the answer you want.
sum(map(eq, mystring, mystring.lower()))
or the one-liner:
#What I am doing here is using a generator expression.
#I think reading it is the best way to understand what is happening.
#For every letter in the input string, check if it is lower, and pass
#that result to sum. sum sees this like any other sequence, but this sequence
#is also 'lazy,' each element is generated as you need it, and it isn't
#stored anywhere. The results are just given to sum.
sum(c.islower() for c in input('enter: '))
You have a typo in your code. Instead of:
if my.string.lower():
It should be:
if ch.islower():
If you have any questions ask below. Good luck!
I'm not sure if this will handle UTF or special characters very nicely but should work for at least ASCII in Python3, using the islower() function.
count=0
mystring=input("enter:")
for ch in mystring:
if ch.islower():
count+=1
print(count)
The correct version of your code would be:
count=0
mystring=input("enter")
for ch in mystring:
if ch.islower():
count += 1
print(count)
The method lower converts a string/char to lowercase. Here you want to know if it IS lowercase (you want a boolean), so you need islower.
Tip: With a bit of wizardry you can even write this:
mystring= input("enter")
count = sum(map(lambda x: x.islower(), mystring))
or
count = sum([x.islower() for x in mystring])
(True is automatically converted to 1 and False to 0)
:)
I think you can use following method:
mystring=input("enter:")
[char.lower() for char in mystring].count( True ) )

Categories