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

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.

Related

Joining results in Python [duplicate]

This question already has answers here:
How do I append one string to another in Python?
(12 answers)
How to concatenate (join) items in a list to a single string
(11 answers)
Which is the preferred way to concatenate a string in Python? [duplicate]
(12 answers)
Closed last month.
Im new to Python, like around an hour and a half into it new.. ive crawled my website using cewl to get a bespoke wordlist for password audits, i also want to combine randomly 3 of these words together.
IE Cewl wordlist ;
word1
word2
word3
word4
using a python script i want to further create another wordlist randomly joining 3 words together IE
word4word2word1
word1word3word4
word3word4word2
so far all ive come up with is;
import random
print(random.choice(open("test.txt").read().split()))
print (random.choice(open("test.txt").read().split()))
print(random.choice(open("test.txt").read().split()))
Whilst this is clearly wrong, it will give me 3 random words from my list i just want to join them without delimiter, any help for a complete novice would be massively appreciated
First thing to do is only read the words once and using a context manager so the file gets closed properly.
with open("test.txt") as f:
lines = f.readlines()
Then use random.sample to pick three words.
words = random.sample(lines, 3)
Of course, you probably want to strip newlines and other extraneous whitespace for each word.
words = random.sample([x.strip() for x in lines], 3)
Now you just need to join those together.
Using your code/style:
import random
wordlist = open("test.txt").read().split()
randomword = ''.join([random.choice(wordlist), random.choice(wordlist), random.choice(wordlist)])
print(randomword)
join is a method of the string type and it will join the elements of a list using the string as a delimiter. In this case we use an empty string '' and join a list made up of random choices from your test.txt file.

Remove spaces and colon from a string [duplicate]

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

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.

Splitting a string after a specific character in python [duplicate]

This question already has answers here:
How to get a string after a specific substring?
(9 answers)
How can I split a URL string up into separate parts in Python?
(6 answers)
Closed 2 years ago.
I wanna split everything comes after = and assigning it into a new variable
example:
https://www.exaple.com/index.php?id=24124
I wanna split whatever comes after = which's in this case 24124 and put it into a new variable.
You can of course split this specific string. rsplit() would be a good choice since you are interested in the rightmost value:
s = "https://www.exaple.com/index.php?id=24124"
rest, n = s.rsplit('=', 1)
# n == '24124'
However, if you are dealing with URLs this is fragile. For example, a url to the same page might look like:
s = "https://www.exaple.com/index.php?id=24124#anchor"
and the above split would return '24124#anchor', which is probably not what you want.
Python includes good url parsing, which you should use if you are dealing with URLS. In this case it's just as simple to get what you want and less fragile:
from urllib.parse import (parse_qs, urlparse)
s = "https://www.exaple.com/index.php?id=24124"
qs = urlparse(s)
parse_qs(qs.query)['id'][0]
# '24124'
Simply you use .split() and then take the second part only
url = 'https://www.exaple.com/index.php?id=24124'
print(url.split('=')[1])
For your specific case, you could do...
url = "https://www.exaple.com/index.php?id=24124"
id_number = url.split('=')[1]
If you want to store id_number as an integer, then id_number = int(url.split('=')[1]) instead.

Python matches the part after a .* at its last occurance [duplicate]

This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Closed 5 years ago.
Im trying to read the server states from the guildwars API. For that i match the servername, then comes an occasional language specifier and a ",\n which i intend to match with .* and after that follows the population. But instead of directly matching the first occurrence of population it instead matches the last one. Can someone tell me why( and how to fix this)?
Edit: I found a workaround. By substituting .* with .{,20} it works.
relevant part of the API
"name": "Riverside [DE]",
"population": "Full"
with urlopen('https://api.guildwars2.com/v2/worlds?ids=all') as api:
s = api.read()
s = s.decode('utf-8')
search = re.search(r'''Riverside.*"population": "''',s,re.S)
print(search)
s = s[search.span()[1]:]
state = re.search(r'[a-zA-Z]*',s)
print(state)
There are two things
You should use .*?(trailing question mark) which will stop at the first instance.I wont think this as good or better solution
Instead once you get the data convert it into JSON and do your manipulation on top of it
import json
with urlopen('https://api.guildwars2.com/v2/worlds?ids=all') as api:
s = api.read()
s = s.decode('utf-8')
jsondata = json.loads(s)
filtered_data = filter(lambda a: str(a["name"]).find("Riverside") > -1,jsondata)
print(filtered_data[0]["population"])

Categories

Resources