lehermj
lehermj

Reputation: 936

How would I get rid of certain characters then output a cleaned up string In python?

In this snippet of code I am trying to obtain the links to images posted in a groupchat by a certain user:

import groupy
from groupy import Bot, Group, Member

prog_group = Group.list().first
prog_members = prog_group.members()
prog_messages = prog_group.messages()
rojer = str(prog_members[4])
rojer_messages = ['none']
rojer_pics = []
links = open('rojer_pics.txt', 'w')

print(prog_group)

for message in prog_messages:
    if message.name == rojer:
        rojer_messages.append(message)
        if message.attachments:
            links.write(str(message) + '\n')

links.close()

The issue is that in the links file it prints the entire message: ("Rojer Doewns: Heres a special one +https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12')>" What I am wanting to do, is to get rid of characters that aren't part of the URL so it is written like so:

"https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12"

are there any methods in python that can manipulate a string like so?

Upvotes: 0

Views: 43

Answers (3)

KingMak
KingMak

Reputation: 1478

>>> string = '("Rojer Doewns: Heres a special one +https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12\')>"'
>>> string.split('+')[1][:-4]
'https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12'

Upvotes: 0

Chris
Chris

Reputation: 22963

This can done using string indices and the string method .find():

>>> url = "(\"Rojer Doewns: Heres a special one +https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12')"
>>> url = url[url.find('+')+1:-2]
>>> url
'https://i.groupme.com/406x1199.png.7679b4f1ee964656bde93448ff9cee12'
>>> 

Upvotes: 0

lehermj
lehermj

Reputation: 936

I just used string.split() and split it into 3 parts by the parentheses:

for message in prog_messages:
    if message.name == rojer:
         rojer_messages.append(message)
        if message.attachments:
            link = str(message).split("'")
            rojer_pics.append(link[1])
            links.write(str(link[1]) + '\n')

Upvotes: 0

Related Questions