简体   繁体   中英

How can i strip strings on Python?

How can i strip the string below?(I just want to create a column to show city and state,you can see the city and state's name after \n)

df['Address']
array(['208 Michael Ferry Apt. 674\nLaurabury, NE 37010-5101',
       '188 Johnson Views Suite 079\nKathleen, CA 48958',
       '9127 Elizabeth Stravenue\nDanieltown, WI 06482-3489', ...,
       '4215 Tracy Garden Suite 076\nJoshualand, VA 01707-9165',
       'USS Wallace\n**FPO AE** 73316',
       '37778 George Ridges Apt. 509\nEast Holly, NV 29290-3595'],
      dtype=object)

You can use regex expressions to get the city name, in your case it would look something like this:

    import re
    example_string = '208 Michael Ferry Apt. 674\nLaurabury, NE 37010-5101'
    
    city = re.findall(r"\n(.*?),", text)
    
    print(city)

However, given that you have... in your array, will probably cause problems, since that's not a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM