Remove spaces and colon from a string [duplicate] - python

This question already has answers here:
How to replace multiple substrings of a string?
(28 answers)
Closed 1 year ago.
I'm trying to remove all the spaces and colon from a given string, using a single function, but I'm unable to achieve these two things in a single function can someone please help me on this?
def normalize_string1(string):
return string.replace(" ", "")
def normalize_string2(string):
return string.replace(":- ", "-")
normalize_string("AIX Server--1uryeu6438shdj:-thsoanfg_321-aq.com")

Write This code for your string. It will definitely work. This is a very common mistakes developer makes while working with strings. Here I am taking a string as an example. You can also do both tasks using a single function using this code.
global string
string = "Hello Everyone :- from YOURNAME"
def dtring(string):
string = string.replace(" ", "")
string = string.replace(":-", "-")
print(string)
dtring(string=string)
I used print statement to show you the changes.
One of the major mistakes was you just changed the value of the string but you had not updated those changes to your original string. You can update that value by using the "string =" statement. I hope this is helpful for you. You may try this program with any string

Related

How I read a word after the # symbol [duplicate]

This question already has answers here:
How to extract the substring between two markers?
(22 answers)
Closed last month.
I'm having a problem. I need to create the #everyone_or_person feature. A bit like discord. But I'll have to be able to read the word after the # and stop reading when there is a ("SPACE"/"_") and check for that word in the list. I've appended a simple version as an example. I knew it would not work but I couldn't think of anything else.
input = input("input: ")
value = input.find("#")
output = input.partition("#")[0]
print(str(output))
I've tried to look up how to do it but to no avail.
simply use split:
test = "Some input with #your_desired_value in it"
result = test.split("#")[1].split(" ")[0]
print(result)
this splits your text at the #, takes the entire string after the #, splits again at the first space, and takes the string before that.

Looking for a way to correctly strip a string [duplicate]

This question already has answers here:
python split() vs rsplit() performance?
(5 answers)
Closed 2 years ago.
I'm using the Spotify API to get song data from a lot of songs. To this end, I need to input the song URI intro an API call. To obtain the song URI's, I'm using another API endpoint. It returns the URI in this form: 'spotify:track:5CQ30WqJwcep0pYcV4AMNc' I only need the URI part,
So I used 'spotify:track:5CQ30WqJwcep0pYcV4AMNc'.strip("spotify:track) to strip away the first part. Only this did not work as expected, as this call also removes the trailing "c".
I tried to built a regex to strip away the first part, but instructions were too complicated and D**K is now stuck in ceiling fan :'(. Any help would be greatly appreciated.
strip() removes all the leading and trailing characters that are in the in the argument string, it doesn't match the string exactly.
You can use replace() to remove an exact string:
'spotify:track:5CQ30WqJwcep0pYcV4AMNc'.replace("spotify:track:", "")
or split it at : characters:
'spotify:track:5CQ30WqJwcep0pYcV4AMNc'.split(":")[-1]
Use simple regex replace:
import re
txt = 'spotify:track:5CQ30WqJwcep0pYcV4AMNc'
pat_to_strip = ['^spotify\:track', 'MNc$']
pat = f'({")|(".join(pat_to_strip)})'
txt = re.sub(pat, '', txt)
# outputs:
>>> txt
:5CQ30WqJwcep0pYcV4A
Essentially the patterns starting with ^ will be stripped from the beginning, and the ones ending with $ will be stripped from the end.
I stripped last 3 letters just as an example.

Converting a string variable to a regular expression in python [duplicate]

This question already has answers here:
How to use a variable inside a regular expression?
(12 answers)
Closed 2 years ago.
I am creating a python function with two inputs: a file and a string, in which user can find the location of the string in the file. I figured the best way to do this would be with regular expressions. I have converted the file to one big string (file_string) earlier in the code. For example, let's say the user wants to find "hello" in the file.
input = "hello"
user_input = "r'(" + input + ")'"
regex = re.compile(user_input)
for match in regex.finditer(file_string):
print(match.start())
Creating a new string with r' ' around the input variable is not working. However, the code works perfectly if I replace user_input with r'hello'. How can I convert the string input the user enters to an expression that can be put into re.compile()?
Thanks in advance.
The r is just part of the syntax for raw string literals, which are useful for simplifying some regular expressions. For example, "\\foo" and r'\foo' produce the same str object. It is not part of the value of the string itself.
All you need to do is create a string with the value of input between ( and ).
input = "hello"
user_input = "(" + input + ")"
More efficiently (if only marginally so)
user_input = "({})".format(input)
Or more simply in recent versions of Python:
user_input = f'({input})'

Why string getting from file is not equal to common string? [duplicate]

This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 6 years ago.
I am on python 3.5 and want to find the matched words from a file. The word I am giving is awesome and the very first word in the .txt file is also awesome. Then why addedWord is not equal to word? Can some one give me the reason?
myWords.txt
awesome
shiny
awesome
clumsy
Code for matching
addedWord = "awesome"
with open("myWords.txt" , 'r') as openfile:
for word in openfile:
if addedWord is word:
print ("Match")
I also tried as :
d = word.replace("\n", "").rstrip()
a = addedWord.replace("\n", "").rstrip()
if a is d:
print ("Matched :" +word)
I also tried to get the class of variables by typeOf(addedWord) and typeOf(word) Both are from 'str' class but are not equal. Is any wrong here?
There are two problems with your code.
1) Strings returned from iterating files include the trailing newline. As you suspected, you'll need to .strip(), .rstrip() or .replace() the newline away.
2) String comparison should be performed with ==, not is.
So, try this:
if addedWord == word.strip():
print ("Match")
Those two strings will never be the same object, so you should not use is to compare them. Use ==.
Your intuition to strip off the newlines was spot-on, but you just need a single call to strip() (it will strip all whitespace including tabs and newlines).

Splitting quotes [duplicate]

This question already has answers here:
RegEx: Grabbing values between quotation marks
(20 answers)
Closed 6 years ago.
Does anyone have any advice for removing separators of split quotes in a piece of text? I am using Python, and am still a beginner.
For example, "Well," he said, "I suppose I could take a break." In this example, the italicized "he said," is the separator, and needs to be removed. Then, the quote needs to be seen as one string within quotations such as, "Well, I suppose I could take a break." I haven't been able to find code similar to this yet, and was hoping someone may be able to point me in the right direction.
Thanks!
In order to get the content only within " in your given string, you may use re library as:
import re
my_string = '"Well," he said, "I suppose I could take a break."'
quoted_string = re.findall(r'\".*?\"', my_string)
# 'quoted_string' is -> ['"Well,"', '"I suppose I could take a break."']
new_string = ''.join(quoted_string).replace('"', '')
# 'new_string' is -> 'Well, I suppose I could take a break.'
You may write the same as one-liner as:
''.join(re.findall(r'\".*?\"', my_string)).replace('"', '')

Categories

Resources