I have a string that loks like "u'mystring'". i'm wondering if ther is a easy way to remove the u'' part of the string?

Recommended Answers

All 6 Replies

s = "u'mystring'"

# assuming it is always u'
s2 = s.replace("u'", "'")
print s2  # 'mystring'

s = "You're sure that would work on this string?"

commented: thanks +7

Try a
print str(unicode_string_var)
This is assuming that all characters in the variable can be displayed for your locale.

s = "You're sure that would work on this string?"

I was afraid of that! Need to modify ...

s = "u'mystring'"

# assuming it is always u' (not u") and s starts with u'
if s.startswith("u'"):
    s2 = s.replace("u'", "'", 1)
print s2  # 'mystring'

To make this more general:

def remove_uni(s):
    """remove the leading unicode designator from a string"""
    if s.startswith("u'"):
        s2 = s.replace("u'", "'", 1)
    elif s.startswith('u"'):
        s2 = s.replace('u"', '"', 1)
    return s2

s = 'u"you\'re my favorite string"'

print remove_uni(s)  # "you're my favorite string"

Great. Now I have to learn "'nicode".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.